poj 1330 最近公共祖先

以前的写法太挫了,现在改了一下,精简了

View Code
 #include<stdio.h>
 #include<string.h>
 const int MAX = 10010;
 #define fi(a, b, c)  for(int a = (b) ; a < (c)  ; a++)
 #define FI(a, b, c)  for(int a = (b) ; a <= (c) ; a++)
 #define fe(a,b) for(int a=(b); a; a = nxt[a]) 
 int f[MAX],nxt[2*MAX],pnt[2*MAX],h[MAX],ind[MAX],H[MAX],E,n;
 bool vis[MAX];
 int find(int x){ return x==f[x]?x:f[x]=find(f[x]);}
 void bd(int h[],int a,int b){
     pnt[++E]=b; nxt[E]=h[a]; h[a]=E;
 }
 void dfs(int u){
     f[u]=u;
     fe(i,h[u]) if(!f[pnt[i]]){
         dfs(pnt[i]);
         f[pnt[i]]=u;
     }
     vis[u]=1;
     fe(i,H[u]){
         if(vis[pnt[i]]){
         printf("%d\n",find(pnt[i])); return ;    
       }
     }
 }
 void init(){
     E=0;
     FI(i,0,n)  nxt[i]=h[i]=H[i]=ind[i]=vis[i]=f[i]=0;
 }
 int main(){
     int t,i,a,b;
     scanf("%d",&t);
     while(t--){
         scanf("%d",&n);
         init();
         fi(i,1,n){
             scanf("%d%d",&a,&b);
             ind[b]++;
             bd(h,a,b);
         }
         scanf("%d%d",&a,&b);
         bd(H,a,b);
         bd(H,b,a);
         FI(i,1,n)if(!ind[i]){
                  dfs(i);
                  break;
         }
     }
     return 0;
 }

 

posted @ 2011-10-24 16:37  Because Of You  Views(289)  Comments(0Edit  收藏  举报