Question Link
题目大意
给一堆边,判断这个图是不是树。
题解
树:1、无环。2、是一棵树,不是森林,只有一个根结点。3、无自环
1、并查集判断环。
2、根节点数,判断树棵。
AC code
#include <iostream>
using namespace std;
#define N 105
int fa[N];
bool flag[N];
int findfa(int x){
return x == fa[x] ? fa[x]:fa[x] = findfa(fa[x]);
}
void unin(int x,int y){
int xfa = findfa(x);
int yfa = findfa(y);
if ( xfa != yfa )
fa[ xfa ] = fa[yfa];
}
int main(){
// freopen("1.txt","r",stdin);
int x,y,i,first;
int t=0;int Case=0;
while(cin>>x>>y){
if(x == -1 && y == -1)
break;
else if(x == 0&&y == 0){ //空树也是一棵树
cout<<"Case "<<t++<<" is a tree."<<endl;
printf("Case %d is a tree.\n",++Case);
continue;
}
else {
for(i=0;i<N;i++){
fa[i] = i; //初始化
flag[i] = false;
}
flag[x] = flag[y] = true;
first = x;
bool istree = true;
if(x == y) istree = false; //自己指向自己,不是一棵树
else{
unin(x,y);
}
while(scanf("%d%d",&x,&y) && x!=0){
flag[x] = flag[y] = true;
if(findfa(x) == findfa(y)) //有共同祖先,x再指向y,就不是一棵树
istree = false;
unin(x,y);
}
for(i=0;i<N;i++){
if(flag[i]&&findfa(i)!=findfa(first)){ //森林不是一棵树
istree = false;
}
}
if(istree) printf("Case %d is a tree.\n",++Case);
// cout<<"Case "<<t++<<" is a tree."<<endl;
else printf("Case %d is not a tree.\n",++Case);
// cout<<"Case "<<t++<<" is not a tree."<<endl;
}
}
return 0;
}