poj1703 Find them, Catch them
poj1182是此题的加强版。若两人属于不同集合则他们所属帮派未知。若属于同一集合,设ra=find(a),若rank[a]==0,则a与ra为同一帮派,反之rank[a]==1,a与ra则分属于不同帮派。另外测下这组数据 1 2 1 A 1 2 答案应该是In different gangs.(在discuss里看到的)。
1 #include<cstdio> 2 #include<string.h> 3 #include<iostream> 4 using namespace std; 5 const int maxn=100001; 6 int p[maxn],rank[maxn],n; 7 8 void init() 9 { 10 int i; 11 for(i=0;i<=n;i++) 12 { 13 p[i]=i; 14 rank[i]=0; 15 } 16 } 17 18 int find(int x) 19 { 20 int temp=p[x]; 21 if(x!=p[x]) 22 { 23 p[x]=find(p[x]); 24 rank[x]=(rank[x]+rank[temp])%2; 25 } 26 return p[x]; 27 } 28 29 void unions(int x,int y,int rx,int ry) 30 { 31 p[ry]=rx; 32 rank[ry]=(rank[x]-rank[y]+3)%2; 33 } 34 int main() 35 { 36 //freopen("test.txt","r",stdin); 37 int T,k; 38 scanf("%d",&T); 39 while(T--) 40 { 41 scanf("%d%d",&n,&k); 42 init(); 43 int i,a,b,ra,rb; 44 char c[2]; 45 for(i=0;i<k;i++) 46 { 47 scanf("%s%d%d",c,&a,&b); 48 ra=find(a); 49 rb=find(b); 50 if(n==2&&c[0]=='A') { printf("In different gangs.\n");continue;} 51 if(c[0]=='D') unions(a,b,ra,rb); 52 if(c[0]=='A') 53 { 54 if(ra==rb) 55 { 56 if(rank[a]==rank[b]) printf("In the same gang.\n"); 57 else printf("In different gangs.\n"); 58 } 59 else printf("Not sure yet.\n"); 60 } 61 } 62 } 63 return 0; 64 }