当前位置: 代码迷 >> 综合 >> POJ 1330 Nearest Common Ancestors (LCA模板题)
  详细解决方案

POJ 1330 Nearest Common Ancestors (LCA模板题)

热度:21   发布时间:2023-11-15 15:07:04.0

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

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define read(x,y) scanf("%d%d",&x,&y)
#define ll long long#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
const int  maxn =1e5+5;
const int mod=1e9+7;
const ll INF =1e18+7;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}int d[maxn];
///链式前向星
struct edge
{int u,nxt;edge(){}edge(int x,int y){u=x,nxt=y;}
}e[maxn<<1];
int head[maxn],tot=0;
void init(){tot=0;memset(head,-1,sizeof(head));}
void add(int x,int y)
{e[tot]=edge(y,head[x]);head[x]=tot++;
}int res,p1,p2,fa[maxn];
int Find(int x){return x==fa[x]?x:fa[x]=Find(fa[x]);}
void tarjan(int u)///离线算法的模板
{fa[u]=u;for(int i=head[u];~i;i=e[i].nxt){int v=e[i].u;tarjan(v);fa[v]=u;}if(u==p1||u==p2){if(u!=p1) swap(p1,p2);if(fa[p2]) res=Find(fa[p2]);}
}int n,u,v;int main()
{int t;scanf("%d",&t);while(t--){init();  scanf("%d",&n);memset(d,0,sizeof(d));memset(fa,0,sizeof(fa));for(int i=0;i<n-1;i++){scanf("%d%d",&u,&v);add(u,v);  d[v]++;}scanf("%d%d",&p1,&p2);for(int i=1;i<=n;i++)  if(d[i]==0) {tarjan(i);printf("%d\n",res);break;}}return 0;
}

 

  相关解决方案