C/C++:
1 #include <map> 2 #include <queue> 3 #include <cmath> 4 #include <vector> 5 #include <string> 6 #include <cstdio> 7 #include <cstring> 8 #include <climits> 9 #include <iostream> 10 #include <algorithm> 11 #define INF 0xffffff 12 using namespace std; 13 14 const int my_max = 100005; 15 int a, b, my_pre[my_max + 2], my_book[my_max + 2]; 16 bool my_flag; 17 18 int my_find(int x) 19 { 20 int n = x; 21 while (n != my_pre[n]) 22 n = my_pre[n]; 23 int i = x, j; 24 while (my_pre[i] != n) 25 { 26 j = my_pre[i]; 27 my_pre[i] = n; 28 i = j; 29 } 30 return n; 31 } 32 33 void my_join(int aa, int bb) 34 { 35 int n1 = my_find(aa), n2 = my_find(bb); 36 if (n1 != n2) my_pre[n1] = n2; 37 else my_flag = false; 38 } 39 40 int main() 41 { 42 while (scanf("%d%d", &a, &b), a != -1 || b != -1) 43 { 44 if (a == 0 && b == 0) 45 { 46 printf("Yes\n"); 47 continue; 48 } 49 for (int i = 1; i <= my_max; ++ i) 50 { 51 my_pre[i] = i; 52 my_book[i] = 0; 53 } 54 my_book[a] = my_book[b] = 1; 55 my_join(a, b); 56 57 my_flag = true; 58 while (scanf("%d%d", &a, &b), a || b) 59 { 60 my_join(a, b); 61 my_book[a] = my_book[b] = 1; 62 } 63 64 int my_cnt = 0; 65 for (int i = 1; i <= my_max; ++ i) 66 { 67 if (my_book[i] && my_pre[i] == i) 68 { 69 my_cnt ++; 70 if (my_cnt >= 2) 71 { 72 my_flag = false; 73 break; 74 } 75 } 76 } 77 78 if (my_flag) 79 printf("Yes\n"); 80 else 81 printf("No\n"); 82 } 83 return 0; 84 }
原文:https://www.cnblogs.com/GetcharZp/p/9452560.html