您的位置:首页 > 其它

Is it a tree(判断是否是树)

2016-09-16 07:43 141 查看
http://bailian.openjudge.cn/practice/1308/
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<string.h>
#include<algorithm>
#define N 100
/*
1判断是否是空树
2判断节点数=边数+1
3判断是否有环(并查集)
*/
using namespace std;
struct E{
int x,y;
}edge
;
int size;
int root
;
int point
;
int cnt;
int findroot(int x)
{
if(root[x]==-1)
return x;
else
{
int tmp=findroot(root[x]);
root[x]=tmp;
return tmp;
}
}
void init()
{
memset(point,0,sizeof(point));
memset(root,-1,sizeof(root));
size=cnt=0;
}

bool solve1()
{//顶点数量=边数量+1
sort(point,point+cnt);
int sum=1;//顶点个数
for(int i=1;i<cnt;i++)
{
if(point[i]!=point[i-1])
sum++;
}
if(sum==size+1)
return true;
else
return false;
}
bool solve2()
{//是否有环(并查集)
for(int i=0;i<size;i++)
{
int u=findroot(edge[i].x);
int v=findroot(edge[i].y);
if(u==v)
{
return false;
}
else
{
root[v]=u;
}
}
return true;
}

int main()
{
int a,b;
int t=0;
init();
while(~scanf("%d%d",&a,&b) && a!=-1 && b!=-1)
{
if(a==0 && b==0)
{//空树
if(size==0)
printf("Case %d is a tree.\n",++t);
else
{//一个测例的结束
if(solve1()&&solve2())
{
printf("Case %d is a tree.\n",++t);
}
else
printf("Case %d is not a tree.\n",++t);

init();
}
}
else
{
edge[size].x=a;
edge[size++].y=b;
point[cnt++]=a;
point[cnt++]=b;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: