您的位置:首页 > 理论基础 > 数据结构算法

数据结构 并查集 Poj 1308

2016-08-07 17:01 323 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: