题目连接:
POJ 1308
利用并查集判断一棵树,不能存在环(就判断是不是两个元素拥有相同的祖先即可),注意空树也是一棵树。
并查集一开始没有用递归来写,总的代码显得很长。
利用并查集判断一棵树,不能存在环(就判断是不是两个元素拥有相同的祖先即可),注意空树也是一棵树。
并查集一开始没有用递归来写,总的代码显得很长。
/*
POJ 1308 Is It A Tree?
测试数据:
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
0 0
1 1 0 0
1 2 1 2 0 0
1 2 2 3 4 5 0 0
1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 0 0
1 2 2 1 0 0
-1 -1
特殊数据的解释
0 0 空树是一棵树
1 1 0 0 不能自己指向自己
1 2 1 2 0 0 重复都不行
1 2 2 3 4 5 森林不算是树
1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1
1 2 2 1 0 0 也是错误的
*/
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXS = 5000;
int father[MAXS],m=1;
bool flag;
void init(){
memset(father,-1,sizeof(father));
flag = true;
}
bool find(int a,int b){ // a 的前辈里有b则 false
bool temp = true ;
while(father[a] > 0){
if (father[a] == b)
temp = false;
a = father[a];
}
return temp;
// if (temp) return false;// a 的前辈里有b则 false
// else return true;
}
void combination(int a,int b){
if (father[b] <= 0 && find(a,b) && a != b) // 父节点 <=0 才有资格有父节点
father[b] = a;
else
flag = false; // 否则拥有多个父亲了,甚至b不能重复被相同的a指向
if (father[a] == -1) //出现了一棵树
father[a] = 0;
}
bool check(){ //true不是森林是树 判断是不是森林
int sum=0; // 记录祖先的个数
for (int i = 0 ; i < MAXS ; i++){
if (father[i] == 0)
sum++;
}
if (sum <= 1)return true;
else return false;
}
int main()
{
freopen("in.txt","r",stdin);
int a,b;
while(1){
init();
int l = 0;
while( cin >> a >> b ,a!=-1 && b!=-1){
if (a==0 && b==0){
if (0 == l) // 如果是空树!!!
flag = true;
break;
}else{
combination(a,b);
}l++;
}
if (a==-1 && b==-1) break;
if (flag && check())
printf("Case %d is a tree.\n",m++);
else
printf("Case %d is not a tree.\n",m++);
}
return 0;
}