判定是否成环,是否只有一个根,是否为空.
代码如下:
#include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> #include <map> #define MAXN 100000 using namespace std; int stk[MAXN+5], top, flag; int set[MAXN+5]; map<int,int>mp; void init() { for (int i = 1; i <= MAXN; ++i) set[i] = i; top = flag = 0; mp.clear(); } int find(int x) { return set[x] = x == set[x] ? x : find(set[x]); } int main() { int x, y, ca = 0; init(); while (scanf("%d %d", &x, &y), x >= 0 && y >= 0) { if (!x && !y) { int k = 0; for (int i = top; i >= 1; --i) { if (set[stk[i]] == stk[i]) { ++k; } } if (k == 1 && !flag || top == 0) { printf("Case %d is a tree.\n", ++ca); } else { printf("Case %d is not a tree.\n", ++ca); } init(); } else { if (!mp.count(x)) { mp[x] = 1; stk[++top] = x; } if (!mp.count(y)) { mp[y] = 1; stk[++top] = y; } int a, b; a = find(x), b = find(y); if (a != b) { set[a] = b; } else { flag = 1; } } } return 0; }