Source Code Problem: 1182 User: zhouxc Memory: 980K Time: 422MS Language: G++ Result: Accepted Source Code #include "iostream" using namespace std; int n,m,x,y,c,test,dist; int p[50001],rank[50001],level[50001]; void Make_set() { for(int i=1;i<=n;i++) { p[i]=i; rank[i]=0; level[i]=0; } } int Find_set(int a) { if(p[a]!=a) { dist+=level[a]; return Find_set(p[a]); } else return p[a]; } int Union(int c1,int c2) { dist=0; int a=Find_set(c1); int dist1=dist%3; dist=0; int b=Find_set(c2); int dist2=dist%3; // cout<<a<<" "<<b<<endl; // cout<<dist1<<" "<<dist2<<endl; cout<<"**********"<<endl; if(c==1) { if(a==b) { if(dist1==dist2) return 1; else return 0; } else { if(rank[a]>rank[b]) { p[b]=a; level[b]=(dist1-dist2+3)%3; } else if(rank[a]<rank[b]) { p[a]=b; level[a]=(dist2-dist1+3)%3; } else { p[b]=a; rank[a]++; level[b]=(dist1-dist2+3)%3; } } } else { if(a==b) { if((dist1-dist2+3)%3==2) return 1; else return 0; } else { if(rank[a]>rank[b]) { p[b]=a; level[b]=(dist1-dist2+4)%3; } else if(rank[a]<rank[b]) { p[a]=b; level[a]=(dist2-dist1+5)%3; } else { p[b]=a; rank[a]++; level[b]=(dist1-dist2+4)%3; } } } return 1; } int main() { int mistake=0; scanf("%d%d",&n,&m); Make_set(); for(int i=1;i<=m;i++) { scanf("%d%d%d",&c,&x,&y); if(x>n||y>n) mistake++; else if(!Union(x,y)) mistake++; } printf("%d/n",mistake); return 0; }