6 8 5 3 5 2 6 4 5 6 0 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 8 6 8 6 4 5 3 5 6 5 2 0 0 -1 -1
Yes Yes No
并查集,判断是否成环
#include <stdio.h> #include <string.h> #define maxn 100010 int per[maxn],vis[maxn],flag; int find(int x){ if(per[x]==x) return per[x]; return per[x]=find(per[x]); } void jion(int x,int y){ x=find(x); y=find(y); if(x!=y) per[y]=x;//per[x]=y就Runtime Error ,Why?? else flag=0;//成环 } int main (){ int n,m,i; while(scanf("%d%d",&n,&m)!=EOF){ if(n==-1 && m==-1) break; if(n==0 && m==0){//特殊情况 printf("Yes\n"); continue; } for(i=1;i<maxn;++i){ vis[i]=0; per[i]=i; } vis[n]=1,vis[m]=1; flag=1; jion(n,m); while(scanf("%d%d",&n,&m)){ if(n==0 && m==0) break; jion(n,m); vis[n]=1,vis[m]=1; } int ans=0; for(i=1;i<maxn;++i){ if(vis[i] && per[i]==i) ans++; if(ans>1){ flag=0;//有多个根节点 } } if(flag) printf("Yes\n"); else printf("No\n"); } return 0; }