//目录

LCA最近公共祖先(POJ1330)

题目链接:http://poj.org/problem?id=1330

解题报告:

先将一个子节点,深搜每一个根节点,并标记。

然后深索另一个子节点,当发现访问过了,就找到了最近的公共祖先。

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

const int maxn = 10005;

bool vis[maxn];
int father[maxn];

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(father,-1,sizeof(father));
        memset(vis,0,sizeof(vis));

        int n;
        scanf("%d",&n);
        int a,b;
        for(int i=0;i<n-1;i++)
        {
            scanf("%d%d",&a,&b);
            father[b]=a;
        }

        scanf("%d%d",&a,&b);
        while(b!=-1)
        {
            vis[b]=true;
            b=father[b];
        }

        while(!vis[a])
            a=father[a];
        printf("%d\n",a);

    }
    return 0;
}

 

posted @ 2016-06-20 20:00  小草的大树梦  阅读(183)  评论(0编辑  收藏  举报