标签:space memory scanf src while pst center each from
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 27316 | Accepted: 14052 |
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
Source
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int num,frist[20010],node[20010],deep[20010],ancestor[20010][17],n; struct mp { int to,next; }map[20010]; void init() { num=0; memset(ancestor,0,sizeof(ancestor)); memset(frist,0,sizeof(frist)); memset(deep,0,sizeof(deep)); memset(node,0,sizeof(node)); memset(map,0,sizeof(map)); } void add(int x,int y) { ++num; map[num].to=y; map[num].next=frist[x];frist[x]=num; } void build(int v) { int i; for(i=frist[v];i;i=map[i].next) { if(!deep[map[i].to]) { ancestor[map[i].to][0]=v; deep[map[i].to]=deep[v]+1; build(map[i].to); } } } void init_ancestor() { int i,j; for(j=1;j<17;++j) for(i=1;i<=n;++i) if(ancestor[i][j-1]) ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1]; return; } int lca(int a,int b) { int i,dep; if(deep[a]<deep[b]) swap(a,b); dep=deep[a]-deep[b]; for(i=0;i<17;++i) if((1<<i)&dep) a=ancestor[a][i]; if(a==b) return a; for(i=16;i>=0;--i) { if(ancestor[a][i]!=ancestor[b][i]) { a=ancestor[a][i]; b=ancestor[b][i]; } } return ancestor[a][0]; } int main() { int T,i,v,w,roof,qv,qw; scanf("%d",&T); while(T--) { init(); scanf("%d",&n); for(i=0;i<n-1;++i) { scanf("%d%d",&v,&w); add(v,w);add(w,v); ancestor[w][0]=v; if(!ancestor[v][0]) roof=v;//找根,根不同答案是不同的。 } deep[roof]=1; build(roof); init_ancestor(); scanf("%d%d",&qv,&qw); printf("%d\n",lca(qv,qw)); } return 0; }
[最近公共祖先] POJ 1330 Nearest Common Ancestors
标签:space memory scanf src while pst center each from
原文地址:http://www.cnblogs.com/fuermowei-sw/p/6166047.html