Nearest Common Ancestors

 

Input

The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case starts with a line containing an integer N , the number of nodes in a tree, 2<=N<=10,000. The nodes are labeled with integers 1, 2,..., N. Each of the next N -1 lines contains a pair of integers that represent an edge --the first integer is the parent node of the second integer. Note that a tree with N nodes has exactly N - 1 edges. The last line of each test case contains two distinct integers whose nearest common ancestor is to be computed.

Output

Print exactly one line for each test case. The line should contain the integer that is the nearest common ancestor.
 
#include<iostream>
#include<cstring>
using namespace std;
int visit[10005],root[10005];
struct node
{
    int f;
    int id;
    node *next;
    
}tree[10005];
int LCA;
void dfs(int x,int y,int p);
int main()
{
    int T,N,x,y,i;
    node *p;
    cin>>T;
    while(T--)
    {
        cin>>N;
        memset(visit,0,sizeof(visit));
        memset(root,0,sizeof(root));
        for(i=1;i<=N;++i)
        {
            tree[i].f=i;
            tree[i].next=NULL;
            tree[i].id=i;
        }
        
        for(i=1;i<=N-1;++i)
        {
            cin>>x>>y;
            root[y]=1;
            p=new node;
            p->id=y;
            p->next=tree[x].next;
            tree[x].next=p;
        }
        
        cin>>x>>y;
        for(i=1;i<=N;++i)
        if(root[i]==0)
        {
            dfs(x,y,i);
            break;
        }
        cout<<LCA<<endl;
    }
}
void dfs(int x,int y,int p)
{
    node *q;
    visit[p]=1;
    if(p==x&&visit[y])
    {
        
        while(tree[y].f!=tree[y].id)
        y=tree[y].f;
        LCA=tree[y].f;
    }
    else if(p==y&&visit[x])
    {
        while(tree[x].f!=tree[x].id)
        x=tree[x].f;
        LCA=tree[x].f;
    }
    else
    {
        q=tree[p].next;
        for(;q;q=q->next)
        if(visit[q->id]==0)
        {
            dfs(x,y,q->id);
            tree[q->id].f=tree[p].id;
        }
    }
}

 

posted on 2013-04-27 21:23  耶稣爱你  阅读(173)  评论(0)    收藏  举报