仍旧裸敲并查集。有这两点注意:
1.输入 0 0 时候要输出YES
2.留心数组的初始化
1 #include <iostream> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cstdio> 5 #include <numeric> 6 #include <algorithm> 7 #include <cctype> 8 #include <string> 9 10 using namespace std; 11 12 const int MAXN = 100001; 13 14 bool flag[MAXN]; 15 int connectedList[MAXN]; 16 bool isOk = true; 17 int nStart, nEnd; 18 19 void Init() { 20 for (int i = 0; i < MAXN; ++i) { 21 connectedList[i] = i; 22 flag[i] = false; 23 } 24 } 25 26 int getFather(int vetex) { 27 int pos = vetex; 28 while(pos != connectedList[pos]) { 29 pos = connectedList[pos]; 30 } 31 return pos; 32 } 33 34 int countListNum() { 35 int count = 0; 36 for (int i = 0; i < MAXN; ++i) { 37 if (flag[i] == true) { 38 if (getFather(i) == i) { 39 ++count; 40 } 41 } 42 } 43 return count; 44 } 45 46 void process() { 47 if( getFather(nStart) == getFather(nEnd)) { 48 isOk = false; 49 return; 50 } 51 if( getFather(nStart) == nStart && getFather(nEnd) == nEnd) { 52 connectedList[nEnd] = nStart; 53 } else if(getFather(nStart) == nStart) { 54 connectedList[nStart] = getFather(nEnd); 55 } else { 56 connectedList[nEnd] = getFather(nStart); 57 } 58 flag[nStart] = true; 59 flag[nEnd] = true; 60 } 61 int main() { 62 while(cin >> nStart >> nEnd) { 63 if(nStart == -1 && nEnd == -1) break; 64 if(nStart || nEnd) { 65 isOk = true; 66 memset(flag, false , sizeof(flag)); 67 Init(); 68 process(); 69 70 while(cin >> nStart >> nEnd, nStart || nEnd) { 71 if(isOk == true) { 72 process(); 73 } 74 } 75 76 if(isOk == true) { 77 int count = 0; 78 count = countListNum(); 79 if(count > 1) { 80 isOk = false; 81 } 82 } 83 } else { 84 isOk = true; 85 } 86 if(isOk == false) { 87 cout << "No" << endl; 88 } else { 89 cout << "Yes" << endl; 90 } 91 } 92 return 0; 93 }