0038 最近公共祖先

#include<stdio.h>
#include<string.h>
const int maxm=10005;
int father[maxm];
bool vis[maxm];
int main()
{
    int n,i,j,k,sum,a,b,t,x,y;
    scanf("%d",&t);                               //輸入測試用例 
    while(t--)
    {
        memset(vis,false,sizeof(vis));            //使vis裏都爲假 
        memset(father,-1,sizeof(father));         //使father裏都爲真 
        scanf("%d",&n);                           //輸入節點數 
        for(i=1;i<n;i++)
        {
            scanf("%d%d",&x,&y);                  //輸入邊 
            father[y]=x;
        }
        scanf("%d%d",&a,&b);                      //輸入需要求的共同祖先 
        while(b!=-1)                              
        {
            vis[b]=true;                           //將b的特殊標記 
            b=father[b];
        }
        while(!vis[a])                              //如果a==b 
            a=father[a];
        printf("%d\n",a);
    }
    return 0;
}
/*
324
5
2 3
3 4
3 1
1 5
3 5
*/
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章