标签:
传送门:http://poj.org/problem?id=1330
题意:很裸的最近公共祖先,看题就知道…模板题。
代码:
/* *********************************************** Author :Torrance_ZHANG Created Time :2016/4/29 22:11:34 File Name :ceshi2.cpp ************************************************ */ #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> typedef long long int LL; using namespace std; const int MAXN=10010; int qx,qy,res; struct Edge{ int to; int next; Edge(){ to=-1; next=-1; } }edge[MAXN]; int deg[MAXN]; //统计入度,找根 int n,cnt,head[MAXN],fa[MAXN],rnk[MAXN],vis[MAXN]; //rnk统计节点的秩,即深度 void add(int u,int v){ edge[cnt].to=v; edge[cnt].next=head[u]; head[u]=cnt; cnt++; } int Find(int x){ return x==fa[x]?fa[x]:fa[x]=Find(fa[x]); } void Tarjan(int x){ fa[x]=x; for(int i=head[x];i!=-1;i=edge[i].next){ Tarjan(edge[i].to); fa[edge[i].to]=x; } if(x==qx||x==qy){ if(x!=qx) swap(qx,qy); if(fa[qy]) res=Find(fa[qy]); } } int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int t; scanf("%d",&t); while(t--){ cnt=0; res=0; memset(head,-1,sizeof(head)); memset(deg,0,sizeof(deg)); memset(fa,0,sizeof(fa)); scanf("%d",&n); for(int i=1;i<n;i++){ int x,y; scanf("%d%d",&x,&y); add(x,y); deg[y]++; } int root=0; scanf("%d%d",&qx,&qy); for(int i=1;i<=n;i++){ if(deg[i]==0){ root=i; break; } } Tarjan(root); printf("%d\n",res); } return 0; }
【POJ 1330】Nearest Common Ancestors(最近公共祖先)
标签:
原文地址:http://www.cnblogs.com/Torrance/p/5450293.html