您的位置:首页 > 其它

Is It A Tree?(并查集)

2012-08-07 08:04 239 查看
判断树是否唯一

1.只有一个根节点,(1)在一棵树上一个根节点。1 2 3 2就是两个根节点(1)只有一棵树

2.不成环,入度不大于1

由于数组运行超界导致wa,这是老毛病了 还一直错

#include<stdio.h>
const int MAXN=1000100;
int father[MAXN],rank[MAXN];

struct Node
{
int x,y;
} node[MAXN];

void Make_set()
{
for(int i=1; i<MAXN; i++)
{
rank[i]=0;
father[i]=i;
}
}

int Find(int x)
{
int r=x;
while(r!=father[r])
{
r=father[r];
}
if(r!=x) father[x]=r;
return father[x];
}

void Union(int x,int y)
{
//秩小的加到大的里
/* if(rank[x]>rank[y])
{
father[y]=x;
}
else
{
if(rank[x]==rank[y])
{
rank[y]++;
}
father[x]=y;
}*/
father[y]=x;
}

int main()
{
int cas,flag,i;
int tes=1;
while(1)
{
cas=flag=0;
while(scanf("%d%d",&node[cas].x,&node[cas].y))
{
if(node[cas].x==-1 && node[cas].y==-1) return 0;
if(node[cas].x==0 && node[cas].y==0) break;
cas++;
}
Make_set();
for(i=0; i<cas; i++)
{
int x=Find(node[i].x);
int y=Find(node[i].y);
if(x==y)
{
flag=1;
}
else Union(x,y);
}
int temp=Find(node[0].x);
for(i=0; i<cas; i++)
{
if(Find(node[i].x)!=temp) flag=1;
if(Find(node[i].y)!=temp) flag=1;
}
if(flag) printf("Case %d is not a tree.\n",tes++);
else printf("Case %d is a tree.\n",tes++);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: