数据结构 并查集 Poj 1308

#include <cstdio>
#include <math.h>
#include <cstring>
int parent[100005]; 
int vis[100005];
int n,m;//用来记录 点的个数  为了判断是否有环 n为点 m为边 
int flag;//是否输入的两个数字已经是 树上的点 
int find(int x)
{
	if(x!=parent[x]) 
	{
		return parent[x]=find(parent[x]);
	}
	else return x;
}
void into()
{
	for(int i=0;i<100005;i++)
	{
		parent[i]=i;
		vis[i]=0;
	}	
	n=0;m=0;flag=0;
}
int main()
{
	int x,y;
	int cas=1;
	into();
	while(scanf("%d%d",&x,&y)!=EOF && x!=-1 &&y!=-1)
	{
		if(x==0 && y==0)
		{
			printf("Case %d is ",cas++);
			//flag 说明 已经在一棵树上了, 重复
			//n-1==m 没有环
			//n==0   坑点,没有点也是树 
			if(!flag && (n-1==m || n==0))
				printf("a tree.\n");
			else printf("not a tree.\n");
			into();
			continue;//一定要跳出去 
		} 
		
		int px=find(x);int py=find(y);
		if(!vis[x]) n++; vis[x]=1;
		if(!vis[y]) n++; vis[y]=1;
		if(px!=py)
		{
			parent[py]=px;
			m++;// 不在一个树上  m为边 
		}
		else  flag=1;
		
		
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值