标签:
http://poj.org/problem?id=1308
题意:判断是否所有的节点只能组成一棵树,也就是判断是否有环。没有说有多少个节点,比较坑了。
注意:1.若当输出只有0 0时,也能构成一棵树,因为空树也是树。
2.所给的节点不能够构成森林(必须只能是一棵树)
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> #include<math.h> #define maxn 110 #define INF 0xfffffff using namespace std; int father[maxn], v[maxn], flag; int Find(int x) { while(x!=father[x]) x = father[x]; return x; } void solve(int a, int b) { v[a] = v[b] = 1; if(a == b) flag = 1; else { int ra = Find(a); int rb = Find(b); if(ra == rb) flag = 1; else father[rb] = ra; } } int main() { int a, b, fist, t=1; while(scanf("%d %d", &a, &b), a!=-1 || b!=-1) { fist = a; memset(v, 0, sizeof(v)); for(int i=1; i<maxn; i++) father[i] = i; flag = 0; if(a==0 && b==0) { printf("Case %d is a tree.\n",t++);//空树也是树; continue; } solve(a, b); while(scanf("%d %d", &a, &b), a+b) { solve(a, b); } for(int i=1; i<maxn; i++) { if(Find(i)!=Find(fist) && v[i]) { flag = 1; break; } } if(!flag) printf("Case %d is a tree.\n", t++); else printf("Case %d is not a tree.\n", t++); } return 0; }
标签:
原文地址:http://www.cnblogs.com/daydayupacm/p/5720474.html