#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 10000+1000;
std::vector<int > tree[maxn];
int indeg[maxn];
int root;
int ancestor[maxn];
bool vst[maxn];
void BuildTree(int node_number)
{
//clear deg and tree
for (int i = 0; i < maxn; ++i)
{
indeg[i] = 0;
tree[i].clear();
}
for (int i = 0; i < node_number; ++i)
{
//make link x-->y
int x,y;
scanf("%d%d",&x,&y);
tree[x].push_back(y);
indeg[y]++;
}
for (int i = 1; i <= node_number; ++i)
{
//find the root of tree
if (indeg[i] == 0)
{
root = i;
break;
}
}
}
int father[maxn];
void make_set()
{
// initialise the set
for (int i = 0; i < maxn; ++i)
{
father[i] = i;
}
}
int getfather(int x)
{
if (x != father[x])
{
father[x] = getfather(father[x]);
}
return father[x];
}
void unionSet(int x,int y)
{
int fx = getfather(x);
int fy = getfather(y);
if(fx != fy)
{
father[fx] = fy;
}
}
bool flag;
void Trajan(int proot,int a,int b)
{
for(int i = 0; i < tree[proot].size(); i++)
{
Trajan(tree[proot][i],a,b);
unionSet(proot,tree[proot][i]);
ancestor[getfather(proot)] = proot;
}
vst[proot] = 1;
if (proot == a && vst[b] && !flag)
{
flag = true;
printf("%d\n", ancestor[getfather(b)]);
return ;
}
if (proot == b && vst[a] && !flag)
{
flag = true;
printf("%d\n", ancestor[getfather(a)]);
return ;
}
}
int main(int argc, char const *argv[])
{
int ncase;
int number;
scanf("%d",&ncase);
while(ncase--)
{
scanf("%d",&number);
BuildTree(number-1);
make_set();
int a,b;
scanf("%d%d",&a,&b);
memset(vst,0,sizeof(vst));
for (int i = 0; i < maxn; i++) ancestor[i] = i;
flag = false;
Trajan(root,a,b);
}
return 0;
}
poj-1330 Nearest Common Ancestors
最新推荐文章于 2021-10-04 18:59:33 发布