ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Nearest Common Ancestors(LCA)(最近公共祖先LCA)

2021-11-12 19:03:32  阅读:133  来源: 互联网

标签:Nearest head Ancestors int void fath deep js LCA


题目链接:

http://poj.org/problem?id=1330

这个问题做法比较多,记录下自己的写法。
1,首先将数据存储在邻接表里,先将数据按照并查集存储,然后将叶子节点的深度全部神深搜出来,存储到深度数组中。
2,然后就是具体做法:
先判断两个数是否在一棵树的同一层上,若不是先调整到同一层上。然后将两个数据在并查集内,同时向上搜寻,直至fath[a]==fath[b];

#include<stdio.h>
#include<iostream>
using namespace std;
#include<cstring>
int head[1000101];
int fath[1000001];
int deep[1000001];
int js;
int root;
int n;
struct edge
{
    int data;
    int next;
} v[100001];
void add(int x,int y)
{
    v[js].next = head[x];
    v[js].data = y;
    head[x] = js;
    js++;
}
void input()
{
    cin>>n;
    memset(head,-1,sizeof head);
    memset(fath,-1,sizeof fath);
    for (int i = 1; i < n; i++)
    {
        int x, y;
        cin >> x >> y;
        add(x,y);
        fath[y] = x;
    }

}
void dfs(int x,int d)
{
    for (int i = head[x]; i != -1; i = v[i].next)
        dfs(v[i].data,d+1);
    deep[x] = d;
}
void predeal()
{
    for(int i=1; i<=n; i++)
        if (fath[i] == -1)
        {
            root = i;
            break;
        }
    dfs(root,0);
}
void solve()
{
    int x, y;
    cin >> x >> y;
    if (deep[x] < deep[y])
    {
        swap(x,y);
    }
    while (deep[x] > deep[y])
        x = fath[x];
    while (x != y)
    {
        x = fath[x];
        y = fath[y];
    }
    printf("%d\n",x);
}
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        input();
        predeal();
        solve();
    }


}

标签:Nearest,head,Ancestors,int,void,fath,deep,js,LCA
来源: https://blog.csdn.net/weixin_46574282/article/details/121293745

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有