标签:
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 20260 | Accepted: 10683 |
Description
Input
Output
Sample Input
2 16 1 14 8 5 10 16 5 9 4 6 8 4 4 10 1 13 6 15 10 11 6 7 10 2 16 3 8 1 16 12 16 7 5 2 3 3 4 3 1 1 5 3 5
Sample Output
4 3
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
#define maxn 10010
vector<int> e[maxn];
int tt,n,vis[maxn],root,fa[maxn][30],deep[maxn];
void dfs(int u)
{
vis[u]=1;
for(int i=0;i<e[u].size();i++)
{
int v=e[u][i];
if(!vis[v])
{
deep[v]=deep[u]+1;
dfs(v);
}
}
}
void bz()
{
int i,j;
for(i=1;(1<<i)<=n;i++)
{
for(j=1;j<=n;j++)
{
fa[j][i]=fa[fa[j][i-1]][i-1];
}
}
}
int LCA(int x,int y)
{
int i,j;
if(deep[x]<deep[y])
swap(x,y);
for(i=0;(1<<i)<=deep[x];i++);
i--;
for(j=i;j>=0;j--)
{
if(deep[x]-(1<<j)>=deep[y])
x=fa[x][j];
}
if(x==y) return y;
for(int j=i;j>=0;j--)
{
if(fa[x][j]!=fa[y][j])
{
x=fa[x][j];
y=fa[y][j];
}
}
return fa[x][0];
}
int main()
{
int x,y;
scanf("%d",&tt);
while(tt--)
{
scanf("%d",&n);
for(int i=0;i<=n;i++)
e[i].clear();
memset(vis,0,sizeof(vis));
memset(fa,0,sizeof(fa));
memset(deep,0,sizeof(deep));
for(int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
fa[y][0]=x;
e[x].push_back(y);
if(fa[x][0]==0)
root=x;
}
fa[root][0]=root;
deep[root]=1;
dfs(root);
bz();
scanf("%d%d",&x,&y);
printf("%d\n",LCA(x,y));
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/a972290869/p/4374020.html