Description
Input
Output
Sample Input
Sample Output
1 #include<cstdio> 2 #include<string.h> 3 using namespace std; 4 //int rank[100010]; 5 int father[100010]; 6 int max1=0; 7 int vis[100010]; 8 int find(int x) 9 { 10 if(x!=father[x]) 11 father[x]=find(father[x]); 12 return father[x]; 13 } 14 bool Union(int x,int y) 15 { 16 int x1=find(x),y1=find(y); 17 if(x1!=y1) 18 { 19 father[y1]=x1; 20 return true; 21 //rank[x]+=rank[y]; 22 //if(max1<rank[x]) max1=rank[x]; 23 //return; 24 } 25 return false; 26 } 27 int main() 28 { 29 int a,b; 30 while(scanf("%d %d",&a,&b)!=EOF&&a!=-1&&b!=-1) 31 { 32 for(int i=1;i<=100010;i++) 33 father[i]=i; 34 if(a==0&&b==0){printf("Yes\n");continue;} //注意continue!!! 35 int min=100000000; 36 int max=0; 37 int flag=1; 38 memset(vis,0,sizeof(vis)); 39 while(a||b) 40 { 41 if(a>max) max=a; 42 if(b>max) max=b; 43 if(a<min) min=a; 44 if(b<min) min=b; 45 vis[a]=1; 46 vis[b]=1; 47 if(!Union(a,b)) flag=0; 48 scanf("%d %d",&a,&b); 49 } 50 if(flag==0) printf("No\n"); 51 else{ 52 int ans=0; 53 for(int i=min;i<=max;i++) 54 if(vis[i]&&father[i]==i) 55 ans++; 56 if(ans==1) printf("Yes\n"); 57 else printf("No\n"); 58 } 59 60 } 61 return 0; 62 }
换了一个小思路
1 #include<cstdio> 2 #include<string.h> 3 using namespace std; 4 //int rank[100010]; 5 int father[100010]; 6 int rank[100010]; 7 int max1=0; 8 //int vis[100010]; 9 int find(int x) 10 { 11 if(x!=father[x]) 12 father[x]=find(father[x]); 13 return father[x]; 14 } 15 bool Union(int x,int y) 16 { 17 int x1=find(x),y1=find(y); 18 if(x1!=y1) 19 { 20 father[y1]=x1; 21 22 rank[x1]+=rank[y1];//记录深度 23 if(max1<rank[x1]) max1=rank[x1]; 24 return true; 25 //rank[x]+=rank[y]; 26 //if(max1<rank[x]) max1=rank[x]; 27 //return; 28 } 29 return false; 30 } 31 int main() 32 { 33 int a,b; 34 while(scanf("%d %d",&a,&b)!=EOF&&a!=-1&&b!=-1) 35 { 36 for(int i=1;i<=100010;i++) 37 { 38 father[i]=i;rank[i]=1; 39 } 40 41 if(a==0&&b==0){printf("Yes\n");continue;} 42 int flag=1; 43 //memset(vis,0,sizeof(vis)); 44 int ans=0; 45 while(a||b) 46 { 47 ans=ans+1;//这是记录输入的边的条数 48 if(!Union(a,b)) flag=0; 49 scanf("%d %d",&a,&b); 50 } 51 // printf("%d %d\n",ans,max1); 52 if(flag==0) printf("No\n"); 53 else if(max1-1==ans) printf("Yes\n"); 54 else printf("No\n"); 55 } 56 return 0; 57 }
原文:http://www.cnblogs.com/angledamon/p/3902793.html