POJ 1308 Is It A Tree?

来源:互联网 发布:用户 网络数据监控 编辑:程序博客网 时间:2024/06/03 20:05

题目:有个很类似的题目,点击打开我的博客

Description

A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties. 

There is exactly one node, called the root, to which no directed edges point. 
Every node except the root has exactly one edge pointing to it. 
There is a unique sequence of directed edges from the root to each node. 
For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not. 

In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.

Input

The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero.

Output

For each test case display the line "Case k is a tree." or the line "Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1).

Sample Input

6 8  5 3  5 2  6 45 6  0 08 1  7 3  6 2  8 9  7 57 4  7 8  7 6  0 03 8  6 8  6 45 3  5 6  5 2  0 0-1 -1

Sample Output

Case 1 is a tree.Case 2 is a tree.Case 3 is not a tree.

这个题目,除了要满足是连通无环图之外,还必须有唯一的根。

每次输入m,n,m是n的父亲,对m不需要检测,只需要检测n。

n要么是第一次出现,要么出现过但是一直是自己的父亲,不能以其他点为父亲。

还有一个隐晦的地方需要注意,如果n满足自己是自己的父亲,还需要判断m是不是n的后代,否则会形成环。

代码:

#include<iostream>#include<cstring>using namespace std;int fa[100001];int num[100001];int sum;int find(int x){int r = x;while (fa[r] != r)r = fa[r];int f;while (fa[x] != x){f = fa[x];fa[x] = r;x = f;}return r;}int main(){int m, n, max1, max2, cas = 1;while (1){bool flag = true;sum = 0, max1 = 0, max2 = 0;while (scanf("%d%d", &m, &n)){if (m == 0 && n == 0)break;if (m == -1 && n == -1)return 0;if (flag == false)continue;if (max2 < m) max2 = m;if (max2 < n) max2 = n;for (int i = max1 + 1; i <= max2; i++)fa[i] = -1;max1 = max2;if (fa[m] < 0){fa[m] = m;num[m] = 1;sum++;}if (fa[n] >= 0){if (fa[n] != n)flag = false;else if (find(m) == n)flag = false;else{num[find(m)] += num[n];fa[n] = m;}}else{fa[n] = m;num[find(m)]++;sum++;}}printf("Case %d", cas++);if (flag && num[find(max2)] == sum)printf(" is a tree.\n");else printf(" is not a tree.\n");}return 0;}

最开始提到的那个题目,虽然和这个题目很像,但是还是有区别的。

有人拿那个题目的代码稍微一改就AC了,我用源代码做了测试,可以AC,

可是却连下面这个例子都算不对,只能说POJ这个题目的judge其实还不完善。

1 2

1 3

4 3

0 0


2 0