首页 > 代码库 > poj 1330 Nearest Common Ancestors (LCA)

poj 1330 Nearest Common Ancestors (LCA)

题意:求两个点的最近公共祖先。


1A大笑

#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#define maxn 100010

using namespace std;

int fa[maxn],lev[maxn],pre[maxn],c1,c2;
vector<int> son[maxn];
bool dfs(int rt,int obj)
{
    for(int i=0;i<son[rt].size();i++)
    {
        int t = son[rt][i];
        pre[t] = rt;
        lev[t] = lev[rt]+1;
        if(t!=obj)
        {
            if(dfs(t,obj))
                return true;
        }
        else return true;
    }
    return false;
}
void solve(int rt)
{
    memset(lev,0,sizeof(lev));
    dfs(rt,c1);
    dfs(rt,c2);
    pre[rt] = -1;
    int x,y;
    if(lev[c1]>=lev[c2])
    {
        x = c1;
        y = c2;
    }
    else
    {
        x = c2;
        y = c1;
    }
    while(lev[x]!=lev[y])
        x = pre[x];
    if(x==y)
        printf("%d\n",y);
    else
    {
        int k,l;
        for(k=pre[x],l=pre[y];k!=l;k=pre[k],l=pre[l]);
        printf("%d\n",k);
    }
}

int main()
{
    int T,n,a,b,rt;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            fa[i] = i;
            son[i].clear();
        }
        for(int i=1;i<n;i++)
        {
            scanf("%d%d",&a,&b);
            son[a].push_back(b);
            fa[b] = a;
        }
        scanf("%d%d",&c1,&c2);
        for(int i=1;i<=n;i++)
        {
            if(fa[i]==i)
            {
                rt = i;
                break;
            }
        }
        solve(rt);
    }
    return 0;
}