仍旧裸敲并查集。有这两点注意:
1.输入 0 0 时候要输出YES
2.留心数组的初始化
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <numeric>
#include <algorithm>
#include <cctype>
#include <string> using namespace std; const int MAXN = ; bool flag[MAXN];
int connectedList[MAXN];
bool isOk = true;
int nStart, nEnd; void Init() {
for (int i = ; i < MAXN; ++i) {
connectedList[i] = i;
flag[i] = false;
}
} int getFather(int vetex) {
int pos = vetex;
while(pos != connectedList[pos]) {
pos = connectedList[pos];
}
return pos;
} int countListNum() {
int count = ;
for (int i = ; i < MAXN; ++i) {
if (flag[i] == true) {
if (getFather(i) == i) {
++count;
}
}
}
return count;
} void process() {
if( getFather(nStart) == getFather(nEnd)) {
isOk = false;
return;
}
if( getFather(nStart) == nStart && getFather(nEnd) == nEnd) {
connectedList[nEnd] = nStart;
} else if(getFather(nStart) == nStart) {
connectedList[nStart] = getFather(nEnd);
} else {
connectedList[nEnd] = getFather(nStart);
}
flag[nStart] = true;
flag[nEnd] = true;
}
int main() {
while(cin >> nStart >> nEnd) {
if(nStart == - && nEnd == -) break;
if(nStart || nEnd) {
isOk = true;
memset(flag, false , sizeof(flag));
Init();
process(); while(cin >> nStart >> nEnd, nStart || nEnd) {
if(isOk == true) {
process();
}
} if(isOk == true) {
int count = ;
count = countListNum();
if(count > ) {
isOk = false;
}
}
} else {
isOk = true;
}
if(isOk == false) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
}
}
return ;
}