题目链接:Is It A Tree?
题意:判断是不是一棵树。
利用并查集看最后是不是都再一个集合内,如果有出现自环也是错的
代码:
#include <stdio.h>
#include <string.h>
const int N = 100005;
int a, b, n, m, vis[N], parent[N], flag;
int find(int x) {
if (x == parent[x])
return x;
return parent[x] = find(parent[x]);
}
void Union(int a, int b) {
if (!vis[a]) n++; vis[a] = 1;
if (!vis[b]) n++; vis[b] = 1;
int pa = find(a);
int pb = find(b);
if (pa != pb) {
parent[pa] = pb;
m++;
}
else {
flag = 1;
}
}
void init() {
n = m = flag = 0;
memset(vis, 0, sizeof(vis));
for (int i = 1; i < N; i++) parent[i] = i;
}
int main() {
int cas = 0;
init();
while (~scanf("%d%d", &a, &b) && a != -1) {
if (a == 0 && b == 0) {
printf("Case %d %s\n", ++cas, (!flag && (m == n - 1 || n == 0))? "is a tree." : "is not a tree.");
init();
continue;
}
Union(a, b);
}
return 0;
}