标签:
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 #define N 100010 5 using namespace std; 6 int per[N], h[N]; 7 void init() 8 { 9 for(int i = 1; i <= N; i++) 10 per[i] = i; 11 } 12 int find(int x) 13 { 14 return x==per[x] ? x : find(per[x]); 15 } 16 int join(int x, int y)//判断是否成环 17 { 18 int fx = find(x); 19 int fy = find(y); 20 if(fx == fy)//因为给的两个点本来就是连通的,如果根节点一样,就成环了 21 return 0; 22 else 23 { 24 per[fx] = fy; 25 return 1; 26 } 27 } 28 int main() 29 { 30 int n, m; 31 while(~scanf("%d%d", &n, &m), n!=-1 && m!=-1) 32 { 33 memset(h, 0, sizeof(h)); 34 if(n == 0 && m == 0) 35 { 36 printf("Yes\n"); 37 continue; 38 } 39 int flag = 1; 40 h[n] = 1; 41 h[m] = 1; 42 init(); 43 join(n, m); 44 while(~scanf("%d%d", &n, &m), n&&m) 45 { 46 int t = join(n, m);//用t记录是否成环 47 if(!h[n]) 48 h[n] = 1; 49 if(!h[m]) 50 h[m] = 1; 51 if(t == 0) 52 flag = 0; 53 } 54 int root = 0; 55 for(int i = 1; i <= N; i++)//判断根节点的个数 56 { 57 if(h[i] && per[i] == i) 58 root++; 59 } 60 if(flag == 0 || root > 1) 61 printf("No\n"); 62 else 63 printf("Yes\n"); 64 65 } 66 return 0; 67 }
标签:
原文地址:http://www.cnblogs.com/digulove/p/4746145.html