POJ 1308 Is It A Tree 解题报告

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值