http://acm.timus.ru/problem.aspx?space=1&num=1329
最近公共祖先
代码:
#include<iostream> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<vector> #include<set> #include<map> #include<string> #include<queue> #include<stack> #include <iomanip> using namespace std; #define LL long long const int INF=0x3f3f3f3f; //priority_queue<int,vector<int>,greater<int> >qt; const int N=50005; int head[N],I; struct node { int j,next; }side[N*2]; vector<int>qt[N]; int f[N]; bool visited[N]; struct question { int l,r; int k; }mem[N]; int findx(int x) { if(f[x]!=x) f[x]=findx(f[x]); return f[x]; } void add(int i,int j) { side[I].j=j; side[I].next=head[i]; head[i]=I++; } void Fans(int x) {//cout<<x<<endl; for(unsigned int i=0;i<qt[x].size();++i) { int w=qt[x][i]; if(mem[w].l==x) { if(f[mem[w].r]!=-1) mem[w].k=findx(mem[w].r); }else { if(f[mem[w].l]!=-1) mem[w].k=findx(mem[w].l); } } } void dfs(int x,int pre) { visited[x]=true; f[x]=x; Fans(x); for(int t=head[x];t!=-1;t=side[t].next) { int j=side[t].j; if(!visited[j]) { dfs(j,x); } } f[x]=pre; } void LCA(int s) { memset(visited,false,sizeof(visited)); memset(f,-1,sizeof(f)); dfs(s,s); } int main() { //freopen("data.in","r",stdin); int n; while(cin>>n) { int l,r; int s; memset(head,-1,sizeof(head)); I=0; while(n--) { cin>>l>>r; if(r==-1) s=l; else add(r,l); } int m; cin>>m; for(int i=1;i<N;++i) qt[i].clear(); for(int i=0;i<m;++i) { cin>>mem[i].l>>mem[i].r; qt[mem[i].l].push_back(i); qt[mem[i].r].push_back(i); } LCA(s); for(int i=0;i<m;++i) { //cout<<mem[i].k<<endl; if(mem[i].l==mem[i].k) cout<<"1"<<endl; else if(mem[i].r==mem[i].k) cout<<"2"<<endl; else cout<<"0"<<endl; } } return 0; }