题目:
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.
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 2 is a tree.
Case 3 is not a tree.
0 0 空树也是一棵树
1 1 0 0 不是树 不能自己指向自己
1 2 1 2 0 0 不是树 不可以重复
1 2 2 3 4 5 不是树 有多个根节点也就是有多颗数不可以
1 1 2 2 3 3 4 4 5 1 不是树 子节点不可以是根节点
#include <stdio.h>
const int N = 1005;
int m,n,pa[N],flag1,cases = 1,k,flag2;
int mapp[N];//记录出现的编号
void init(){
for(int i = 1; i <= N-1 ; i++){
pa[i] = i;
mapp[i] = 0;
}
flag1 = 1;
flag2 = 1;
}
int get_parent(int x){
return pa[x] == x ? x : get_parent(pa[x]);
}
void merge(int x,int y){
mapp[x] = 1;//编号出现记为1
mapp[y] = 1;
int px = get_parent(x);
int py = get_parent(y);
if(px != py)
pa[py] = pa[px];
}
void judge(int x,int y){
if(pa[y] != y)//判断子节点是否已经有父节点
flag1 = 0;
else
if(get_parent(x) == y)//判断子节点是否为根节点
flag1 = 0;
}
int main(){
while(1){
init();
int i,j;
while(scanf("%d%d",&m,&n) != EOF){
if(m < 0 && n < 0)
return 0;
if(m == 0 && n == 0){
if(k == 0)//记录是不是空树
printf("Case %d is a tree.\n", cases++);//空树也可以
break;
}
k++;
if(m == n)//两个结点不能相等
flag2 = 0;
judge(m,n);
if(flag1){
merge(m,n);
flag1 = 1;
}
else
flag2 = 0;
}
if(k == 0)
continue;
for(i = 1;i <= N-1;i++)//得到根节点
if(mapp[i] == 1){
j = get_parent(i);
break;
}
for(int q = i+1 ;q <= N-1; q++)//判断是否有多个根节点,即是否只有一个树
if(mapp[q] == 1 && j != get_parent(q)){
flag2 = 0;
break;
}
if(flag2)
printf("Case %d is a tree.\n",cases++);
else
printf("Case %d is not a tree.\n",cases++);
k = 0;//标记还原
}
return 0;
}