标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3926
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<cmath> 6 #include<algorithm> 7 #define inf 0x7fffffff 8 using namespace std; 9 const int maxn=10000+10; 10 11 int n,m,n2,m2; 12 int father[maxn],d[maxn],isCircle[maxn]; 13 struct node 14 { 15 int num,isCircle; 16 friend bool operator < (node a,node b) 17 { 18 if (a.num!=b.num) return a.num>b.num; 19 return a.isCircle>b.isCircle; 20 } 21 }an[maxn],bn[maxn]; 22 23 int findset(int x) 24 { 25 if (x==father[x]) return x; 26 return father[x]=findset(father[x]); 27 } 28 void Union(int x,int y) 29 { 30 x=findset(x) ;y=findset(y) ; 31 if (x==y) {isCircle[x]=1;return;} 32 if (d[x]>d[y]) 33 { 34 father[y]=x; 35 d[x] += d[y]; 36 } 37 else 38 { 39 father[x]=y; 40 d[y] += d[x]; 41 } 42 } 43 44 int main() 45 { 46 int t,ncase=1; 47 scanf("%d",&t); 48 while (t--) 49 { 50 scanf("%d%d",&n,&m); 51 memset(isCircle,0,sizeof(isCircle)); 52 for (int i=1 ;i<=n ;i++) father[i]=i,d[i]=1; 53 int u,v; 54 for (int i=0 ;i<m ;i++) 55 { 56 scanf("%d%d",&u,&v); 57 Union(u,v); 58 } 59 int cnt=0,cnt2=0; 60 for (int i=1 ;i<=n ;i++) if (father[i]==i) 61 { 62 an[cnt].num=d[i] ;an[cnt].isCircle=isCircle[i]; 63 cnt ++ ; 64 } 65 sort(an,an+cnt); 66 67 scanf("%d%d",&n2,&m2); 68 memset(isCircle,0,sizeof(isCircle)); 69 for (int i=1 ;i<=n2 ;i++) father[i]=i,d[i]=1; 70 for (int i=0 ;i<m2 ;i++) 71 { 72 scanf("%d%d",&u,&v); 73 Union(u,v); 74 } 75 for (int i=1 ;i<=n2 ;i++) if (father[i]==i) 76 { 77 bn[cnt2].num=d[i] ;bn[cnt2].isCircle=isCircle[i]; 78 cnt2++; 79 } 80 sort(bn,bn+cnt2); 81 82 printf("Case #%d: ",ncase++); 83 if (n!=n2 || m!=m2 || cnt!=cnt2) {printf("NO\n");continue; } 84 int flag=0; 85 for (int i=0 ;i<cnt ;i++) 86 { 87 if (an[i].num != bn[i].num) {flag=1;break; } 88 if (an[i].isCircle != bn[i].isCircle) {flag=1;break; } 89 } 90 if (flag) printf("NO\n"); 91 else printf("YES\n"); 92 } 93 return 0; 94 }
标签:
原文地址:http://www.cnblogs.com/huangxf/p/4395045.html