nyoj 129 树的判定
并查集+欧拉
树的判定
时间限制:1000 ms | 内存限制:65535 KB
难度:4
- 描述
-
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.
- 输入
- 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 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 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.
此题判断是否为树,但是又加入了方向,首先什么是树?
1、只有一个根节点
2、只有唯一的一条路从根节点到其余节点
3、任意两点之间也只有一条通路
再来判断方向
1、每个节点只能有一个入度#include<stdio.h> #include<string.h> #define MAX 10100 #define maxn(a,b)(a>b?a:b) int set[MAX],ru[MAX],chu[MAX]; int find(int fa) { int t; int ch=fa; while(fa!=set[fa]) fa=set[fa]; while(ch!=fa) { t=set[ch]; set[ch]=fa; ch=t; } return fa; } void mix(int x,int y) { int fx,fy; fx=find(x); fy=find(y); if(fx!=fy) set[fx]=fy; } int main() { int n,m,j,i,sum,a,b,k,max,wrong,mistake; k=1; while(1) { max=0; memset(set,0,sizeof(set)); memset(ru,0,sizeof(ru)); mistake=0; while(scanf("%d%d",&a,&b)&&a!=0&&b!=0) { if(a==-1&&b==-1) return 0; if(set[a]==0) set[a]=a; if(set[b]==0) set[b]=b; if(max<maxn(a,b)) max=maxn(a,b); ru[b]++; if(find(a)==find(b))//两个节点在合并之前已经联通 { mistake=1; } mix(a,b); } if(mistake) printf("Case %d is not a tree.\n",k++); else { sum=0;wrong=0; for(i=1;i<=max;i++) { if(ru[i]>1) //节点的入度大于1不符合树的要求 { wrong=1; break; } if(set[i]==i)//判断根节点个数 { sum++; if(sum>1) { wrong=1; break; } } } if(wrong) printf("Case %d is not a tree.\n",k++); else printf("Case %d is a tree.\n",k++); } } return 0; }