Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
为什么并查集会超时啊?带路径压缩#include "STDIO.h" #include "memory.h" #define M 100001 int group=-1; int criminal[M]; int enemy[M]; int stack[M],top=0; void Update(int x,int y); int Query(int x,int y); int Find(int x); void Union(int x,int y); inline int min(int a,int b){return a<b?a:b;} int main(int argc, char* argv[]) { int T; scanf("%d",&T); int n,m; while (T--) { scanf("%d%d",&n,&m); memset(criminal,0,sizeof(criminal)); memset(enemy,0,sizeof(enemy)); int i,x,y; char c; for(i=1;i<=m;i++) { scanf(" %c%d%d",&c,&x,&y); switch(c) { case 'D': Update(Find(x),Find(y)); break; case 'A': if(x==y) { printf("In the same gang.\n"); continue; } int k=Query(Find(x),Find(y)); switch(k) { case 1: printf("Not sure yet.\n"); break; case 2: printf("In the same gang.\n"); break; case 3: printf("In different gangs.\n"); break; } break; } } } return 0; } void Update(int x,int y){ int k1=min(criminal[x],criminal[y]); int k2=criminal[x]+criminal[y]-k1; if( (k1+1==k2&&(-k2)%2 ) || (k1==k2&&k2!=0) ) return; if(enemy[x]==0&&enemy[y]==0) { criminal[x]=group; criminal[y]=group-1; enemy[x]=y; enemy[y]=x; group-=2; } else if(enemy[x]==0&&enemy[y]!=0) { Union(enemy[y],x); enemy[y]=x; } else if(enemy[x]!=0&&enemy[y]==0) { Union(enemy[x],y); enemy[y]=x; } else { Union(enemy[x],y); Union(x,enemy[y]); } } int Find(int x) { top=0; while (criminal[x]>0) { stack[top++]=x; x=criminal[x]; } while (top>0) { criminal[stack[--top]]=x; } return x; } void Union(int x,int y) { criminal[y]=Find(x); } int Query(int x,int y) { int k1=min(criminal[x],criminal[y]); int k2=criminal[x]+criminal[y]-k1; if(k1+1==k2 && (-k1)%2==0 ) return 3; else if(k1==k2&& k1!=0) return 2; else return 1; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator