poj 1330 分类: poj 2015-04-02 22:31 31人阅读 评论(0) 收藏
LCA倍增,以前写过离线Tarjan,不多说
#include<map>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>
const int MAXN = 10005 , logN = 15;
int n;
struct Edge{int v,next;}edge[MAXN<<1] = {0};int el = 0;
int head[MAXN] = {0}, fa[MAXN][logN] = {0} , dep[MAXN] = {0};
bool hash[MAXN] = {0};
void newedge(int u,int v)
{
++el; edge[el].v = v;
edge[el].next = head[u],head[u] = el;
}
void build(int a)
{
dep[a] = dep[fa[a][0]] + 1;
for(int i = head[a]; i; i = edge[i].next)
{
int p = edge[i].v;
if(p == fa[a][0])continue;
fa[p][0] = a; build(p);
}
}
void prelca()
{
for(int j = 1 ; j < logN; j++)
for(int i = 1; i <= n ; i++)
fa[i][j] = fa[fa[i][j-1]][j-1];
}
int getLCA(int u,int v)
{
if(dep[u] > dep[v])std::swap(u,v);
for(int i = logN - 1; i >= 0 ; i--)
if(dep[fa[v][i]] >= dep[u]) v = fa[v][i];
if(u == v) return u;
for(int i = logN - 1; i >= 0 ; i--)
if(fa[u][i] != fa[v][i])u = fa[u][i],v = fa[v][i];
return fa[v][0];
}
int main()
{
int T;
#ifndef ONLINE_JUDGE
freopen("poj1330.in","r",stdin);
freopen("poj1330.out","w",stdout);
#endif
scanf("%d",&T);
while(T--)
{
el = 0;
memset(head,0,sizeof(head));
memset(hash,false,sizeof(hash));
int a ,b , root;
scanf("%d",&n);
for(int i = 1 ; i < n; i++)
{
scanf("%d%d",&a,&b);
newedge(a,b); hash[b] = true;
}
for(int i = 1; i <= n; i++)
if(hash[i] == false){root = i;break;}
fa[root][0] = 0;
build(root); prelca();
scanf("%d%d",&a,&b);
printf("%d\n",getLCA(a,b));
}
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。