注意:如果第一个输入 0 0,printf("Yes\n");
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> #include<math.h> using namespace std; int per[1000005]; bool vis[1000005]; int find(int x)//找根节点; { int i = x; while(i != per[i]) { i = per[i]; } return i; } void join(int x,int y)//合并; { per[x] = y; } void init()//初始化; { for(int i = 0; i < 100005; i ++) { per[i] = i; vis[i] = false; } } int main() { int x,y; while(scanf("%d%d",&x,&y)!= EOF) { if(x == -1 && y == -1) break; if(x == 0 && y == 0)//特判开始为0的情况; { printf("Yes\n"); continue; } init(); vis[x] = true; vis[y] = true; int flag = 0; int maxn = 0; while(x!= 0 && y!= 0) { int s = find(x); int e = find(y); if(s == e)//判断是否成环; { flag = 1; } else join(s,e); scanf("%d%d",&x,&y); vis[x] = true; vis[y] = true; maxn = max(maxn,x); maxn = max(maxn,y); } //printf("%d",flag); if(flag == 1) { printf("No\n"); continue; } int cnt = 0; for(int i = 1; i <= maxn; i ++) { if(vis[i] && per[i] == i) //判断是否连通; cnt ++; } //printf("%d",cnt); if(cnt != 1) { printf("No\n"); continue; } printf("Yes\n"); } return 0; } 如有错误,欢迎指出~