PKU1330+LCA
简单的LCA。。。
dfs里fa的判断很重要呀。。。亲。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 LCA 3 */ 4 #include<stdio.h> 5 #include<string.h> 6 #include<stdlib.h> 7 #include<algorithm> 8 #include<iostream> 9 #include<queue> 10 #include<map> 11 #include<math.h> 12 using namespace std; 13 typedef long long ll; 14 //typedef __int64 int64; 15 const int maxn = 10005; 16 const int inf = 0x7fffffff; 17 const double pi=acos(-1.0); 18 const double eps = 1e-8; 19 int deep[ maxn ],ace[ maxn ],fa[ maxn ]; 20 //int dis[ maxn ]; 21 struct node{ 22 int u,next; 23 }edge[ maxn<<4 ]; 24 int cnt,head[ maxn ]; 25 void init(){ 26 cnt = 0; 27 memset( fa,0,sizeof( fa ) ); 28 memset( head,-1,sizeof( head ) ); 29 } 30 void addedge( int a,int b){ 31 edge[ cnt ].u = b; 32 edge[ cnt ].next = head[ a ]; 33 head[ a ] = cnt++; 34 } 35 void dfs( int now,int now_father,int now_ace,int now_deep/*,int now_dis*/ ){ 36 fa[ now ] = now_father; 37 ace[ now ] = now_ace; 38 deep[ now ] = now_deep; 39 //dis[ now ] = now_dis; 40 for( int i=head[ now ];i!=-1;i=edge[ i ].next ){ 41 int v = edge[ i ].u; 42 //if( fa[v]==0 ){ 43 dfs( v,now,now_ace,now_deep+1/*,now_dis+edge[ i ].val*/ ); 44 //} 45 } 46 } 47 int find( int x,int y ){ 48 if( x==y ) return x; 49 if( deep[x]>deep[y] ) return find( fa[x],y ); 50 else return find( x,fa[y] ); 51 } 52 int main(){ 53 int ca; 54 scanf("%d",&ca); 55 while( ca-- ){ 56 int n; 57 scanf("%d",&n); 58 int a,b; 59 init(); 60 for( int i=0;i<n-1;i++ ){ 61 scanf("%d%d",&a,&b); 62 addedge( a,b ); 63 } 64 scanf("%d%d",&a,&b); 65 for( int i=1;i<=n;i++ ){ 66 if( fa[i]==0 ){ 67 dfs( i,-1,i,0/*,0*/ ); 68 } 69 } 70 /* 71 for( int i=1;i<=n;i++ ){ 72 printf("fa[%d]=%d\n",i,fa[i]); 73 } 74 */ 75 int father = find( a,b ); 76 printf("%d\n",father); 77 } 78 return 0; 79 }
keep moving...