There are the following pitfalls:
1. The end input is not necessarily-1. The description in the question only says that the ownership value is positive.
2. Whether a tree is composed cannot only determine whether there is only one root node, no loops, but also whether the inbound degree of each node must be 1. Otherwise, it is not a tree.
(Tree properties can also be used without loops: knots = edge tree + 1)
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstring> 4 #include <cctype> 5 #include <cmath> 6 #include <string> 7 #include <cstdio> 8 #include <algorithm> 9 #include <numeric>10 using namespace std;11 12 const int maxn = 25;13 14 int father[maxn];15 int eage[maxn];16 bool vis[maxn], flag = 0;17 int sum = 0;18 19 int getFather (int x) {20 while (father[x] != x) {21 x = father[x];22 }23 return x;24 }25 26 void Union (int p, int q) {27 int x = getFather (p);28 int y = getFather (q);29 if (x != y) {30 father[y] = x;31 sum ++;32 } else {33 flag = 0;34 }35 }36 37 int main () {38 int x, y, cur = 0;39 while (cin >> x >> y) {40 if (x < 0 && y < 0) break;41 if (x == 0 && y == 0) {42 printf("Case %d is a tree.\n", ++ cur);43 continue;44 } else {45 flag = 1;46 memset(vis, 0, sizeof(vis));47 memset(eage, 0, sizeof(eage));48 for (int i = 0; i < maxn; ++ i) {49 father[i] = i;50 }51 vis[x] = vis[y] = 1;52 Union(x, y);53 eage[y] ++;54 while (cin >> x >> y) {55 if (x + y == 0) break;56 vis[x] = vis[y] = 1;57 Union(x, y);58 eage[y] ++;59 }60 sort(eage, eage + maxn, greater<int>());61 int xx = 0;62 if (eage[0] > 1) flag = 0;63 for (int i = 1; i < maxn; ++ i) {64 if (vis[i] && father[i] == i) {65 xx ++;66 if (xx > 1) {flag = 0; break;}67 }68 }69 /*for (int i = 1 ; i < maxn; ++ i) {70 cout << vis[i] << " " ;71 }*/72 73 if (flag) printf("Case %d is a tree.\n", ++ cur);74 else printf("Case %d is not a tree.\n", ++ cur);75 }76 }77 return 0;78 }