【HDU1325】Is It A Tree?(并查集基础题)

时间:2023-11-21 21:57:44

有以下坑点:

1.结束输入不一定-1,题目中的叙述只是说所有权值都为正值。

2.是否构成一棵树不能只判断是否只有一个根节点,没有环路,而且还需要判断每个节点的入度一定是1,不然就不是一棵树。

(无环路也可用树的性质:结点数 = 边树 + 1 来取代)

 #include <iostream>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <string>
#include <cstdio>
#include <algorithm>
#include <numeric>
using namespace std; const int maxn = ; int father[maxn];
int eage[maxn];
bool vis[maxn], flag = ;
int sum = ; int getFather (int x) {
while (father[x] != x) {
x = father[x];
}
return x;
} void Union (int p, int q) {
int x = getFather (p);
int y = getFather (q);
if (x != y) {
father[y] = x;
sum ++;
} else {
flag = ;
}
} int main () {
int x, y, cur = ;
while (cin >> x >> y) {
if (x < && y < ) break;
if (x == && y == ) {
printf("Case %d is a tree.\n", ++ cur);
continue;
} else {
flag = ;
memset(vis, , sizeof(vis));
memset(eage, , sizeof(eage));
for (int i = ; i < maxn; ++ i) {
father[i] = i;
}
vis[x] = vis[y] = ;
Union(x, y);
eage[y] ++;
while (cin >> x >> y) {
if (x + y == ) break;
vis[x] = vis[y] = ;
Union(x, y);
eage[y] ++;
}
sort(eage, eage + maxn, greater<int>());
int xx = ;
if (eage[] > ) flag = ;
for (int i = ; i < maxn; ++ i) {
if (vis[i] && father[i] == i) {
xx ++;
if (xx > ) {flag = ; break;}
}
}
/*for (int i = 1 ; i < maxn; ++ i) {
cout << vis[i] << " " ;
}*/ if (flag) printf("Case %d is a tree.\n", ++ cur);
else printf("Case %d is not a tree.\n", ++ cur);
}
}
return ;
}