1896: 树的判定(并查集)

来源:互联网 发布:北京一元洗车软件 编辑:程序博客网 时间:2024/06/03 15:47

1896: 树的判定

时间限制: 1 Sec  内存限制: 64 MB
提交: 3  解决: 3
[提交][状态][讨论版][Edit] [TestData]

题目描述

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.

输入

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. The number of test cases will not more than 20,and the number of the node will not exceed 10000. The inputs will be ended by a pair of -1.

输出

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).

样例输入

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

样例输出

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

提示

nyoj129

/*测试数据1: 0 0 空树是一棵树2: 1 1 0 0 不是树 不能自己指向自己3: 1 2 1 2 0 0 不是树....自己开始一直在这么WA  好郁闷 重复都不行呀~~55554: 1 2 2 3 4 5 不是树  森林不算是树(主要是注意自己)5: 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1  注意 一个节点在指向自己的父亲或祖先 都是错误的 即 9-->1 错6: 1 2 2 1 0 0 也是错误的 */#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define N 11000int f[N];int mark[N];int maxx;//节点最大值 int flag;//标记,为0表示不是树 void init(){for(int i=0;i<N;i++)f[i]=i;memset(mark,0,sizeof(mark));maxx=0;flag=1;}int find(int x){return f[x]==x?x:x=find(f[x]);}void merge(int u,int v){    int t1=find(u);    int t2=find(v);    //v!=t2,说明其已经有了一个父节点,//t1==t2,说明u的根节点指向它自己 不符合要求     if(v!=t2||t1==t2)   flag=0;    if(t1!=t2)  f[t2]=t1;}int main(){int n,m;int Case=1;init();//初始化不能忘 while(scanf("%d%d",&n,&m)!=EOF){if(n==-1&&m==-1)break;if(n==0&&m==0){int dp=0;for(int i=1;i<=maxx;i++)if(mark[i]&&f[i]==i)dp++;if(dp>=2||flag==0)printf("Case %d is not a tree.\n",Case++);else printf("Case %d is a tree.\n",Case++);init();//初始化 continue;}maxx=max(maxx,max(n,m));mark[n]=mark[m]=1;merge(n,m);}  }