并查集。需要考虑入度。
#include <stdio.h>
#include <string.h> #define MAXNUM 10005 int bin[MAXNUM];
int degree[MAXNUM];
int nums[MAXNUM]; int find(int x) {
int r = x; while (bin[r] != r)
r = bin[r]; return r;
} int main() {
int x, y, fx, fy, n, case_n = ;
int i, flg; while () {
scanf("%d %d", &x, &y);
if (x< && y<)
break;
memset(degree, , sizeof(degree));
n = ;
++case_n;
if (x== && y==) {
printf("Case %d is a tree.\n", case_n);
continue;
}
for (i=; i<MAXNUM; ++i)
bin[i] = i;
fx = find(x);
fy = find(y);
bin[fy] = fx;
degree[y]++;
flg = ;
nums[n++] = x;
nums[n++] = y;
while () {
scanf("%d %d", &x, &y);
if (x== && y==)
break;
fx = find(x);
fy = find(y);
if (fx != fy) {
bin[fy] = fx;
degree[y]++;
} else {
bin[fy] = fx;
degree[y]++;
flg = ;
}
nums[n++] = x;
nums[n++] = y;
}
fx = find(nums[]);
for (i=; i<n; ++i) {
fy = find(nums[i]);
if (fx != fy) {
flg = ;
break;
}
}
for (i=; i<n; ++i) {
if (degree[nums[i]] > ) {
flg = ;
break;
}
}
if (flg)
printf("Case %d is a tree.\n", case_n);
else
printf("Case %d is not a tree.\n", case_n);
} return ;
}