POJ 1308(并查集判断树)

1.根节点只能有一个,即每个节点的祖宗都相同

2.根节点的入度为0,其他节点为1

3.在一个集合的节点,如果再次合并,必定产生环路

4.输入0 0,即空树也是树


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define N 100005

int par[N];
int rank[N];

void init(int tn)
{
	for(int i=1;i<=tn;i++)par[i]=i,rank[i]=0;
}

int find(int x)
{
	if(par[x]==x)return x;
	return par[x]=find(par[x]);
}

void unite(int x,int y)
{
	x=find(x);
	y=find(y);
	if(x==y)return;
	if(rank[x]<rank[y])par[x]=y;
	else 
	{
		par[y]=x;
		if(rank[x]==rank[y])rank[x]++;
	}
}

bool same(int x,int y)
{
	return find(x)==find(y);
}

int max(int x,int y)
{
	return x>y?x:y;
}

int x[N],y[N],cnt;
int vis[N],vis2[N];
int maxn;

int main()
{
	int tcase=1,i;
	while(scanf("%d%d",&x[0],&y[0])!=EOF)
	{
		if(x[0]==0&&y[0]==0)
		{
			printf("Case %d is a tree.\n",tcase++);
			continue;
		}
		if(x[0]==-1&&y[0]==-1)break;
		maxn=max(x[0],y[0]);
		memset(vis,0,sizeof vis);
		memset(vis2,0,sizeof vis2);
		vis[y[0]]++;
		vis2[x[0]]=vis2[y[0]]=1;
		bool flag=true;
		cnt=1;
		while(scanf("%d%d",&x[cnt],&y[cnt]))
		{
			if(x[cnt]==0&&y[cnt]==0)break;
			maxn=max(maxn,x[cnt]);
			maxn=max(maxn,y[cnt]);
			vis[y[cnt]]++;
			vis2[x[cnt]]=vis2[y[cnt]]=1;
			if(vis[y[cnt]]>1)flag=false;
			cnt++;
		}
		if(!flag)
		{
			printf("Case %d is not a tree.\n",tcase++);
		}
		else
		{
			int i;
			init(maxn);
			for(i=0;i<cnt;i++)
			{
				if(!flag)break;
				if(same(x[i],y[i]))flag=false;
				else
				{
					unite(x[i],y[i]);
				}
			}
			if(!flag)
			{
				printf("Case %d is not a tree.\n",tcase++);
			}
			else
			{
				int fx=find(maxn);
				for(i=1;i<=maxn;i++)
				{
					if(!vis2[i])continue;
					if(fx!=find(i))flag=false;
				}
				if(!flag)
				{
					printf("Case %d is not a tree.\n",tcase++);
				}
				else printf("Case %d is a tree.\n",tcase++);
			}
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值