题目链接: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;
}

 

相关文章:

  • 2021-12-07
  • 2021-11-03
  • 2022-12-23
猜你喜欢
  • 2021-09-08
  • 2021-07-19
  • 2021-09-25
  • 2021-10-17
  • 2022-01-21
  • 2021-11-30
相关资源
相似解决方案