您的位置:首页 > 其它

hdu 1325 Is It A Tree?

2013-05-14 10:52 288 查看
[align=left]Problem Description[/align]
A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties.
There is exactly one node, called the root, to which no directed edges point.

Every node except the root has exactly one edge pointing to it.

There is a unique sequence of directed edges from the root to each node.

For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not.

#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;

map<int,int>my_map;
map<int,int>my_map2;
int f[111111];
int s;
int cnt;
int sum;

void init()
{
int i;
for(i=1;i<=100000;i++)
{
f[i]=i;
}
my_map.clear();
my_map2.clear();
s=0;
cnt=0;
sum=0;
}

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

void Union(int a,int b)
{
f[b]=a;
}

int main()
{
int a,b;
bool flag=false;
init();
int count=1;
while(~scanf("%d%d",&a,&b))
{
if(a==0 && b==0)
{
if(flag)
{
printf("Case %d is not a tree.\n",count++);
flag=false;
}
else
{
if((sum==(cnt-1) && s==(cnt-1)) || (sum==0 && cnt==0))
{
printf("Case %d is a tree.\n",count++);
}
else
{
printf("Case %d is not a tree.\n",count++);
}
}
init();
continue;
}
if(a<0 && b<0)
{
break;
}
if(!my_map[a])
{
my_map[a]++;
cnt++;
}
if(!my_map2[b])
{
my_map2[b]++;
s++;
}
if(!my_map[b])
{
my_map[b]++;
cnt++;
}

int x,y;
if(a==b)
continue;
x=find(a);
y=find(b);
if(x==y)
{
flag=true;
}
else
{
Union(x,y);
sum++;
}
}
return 0;
}


View Code
并查集题目;

值得注意几点:

1、判断是否出现环,使用并查集模板可以实现。

2、判断是否N个点有且仅有N-1条边。

3、题目要求除根节点外,所有的节点都必须有且仅有一条边指向该节点。

4、从根节点可以通过箭头指向访问到每一个节点,也就是第二条注意说的,必须是联通的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: