您的位置:首页 > 其它

hdu 1325 Is It A Tree?(并查集)

2012-10-14 19:37 357 查看

Is It A Tree?

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 421 Accepted Submission(s): 157
[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.

View Code

#include <stdio.h>

const int max_num = 100000+10;
typedef struct
{
int num,root,conn;//数据、根、入度
}Node;

Node node[max_num];

void init()
{
for(int i = 0; i < max_num; i++)
{
node[i].conn = 0;//入度初始化为0
node[i].root= i;//根记录为自身
node[i].num=0;//标记数字是否被使用过,0:没有被使用过,1:使用过了
}
}

int find_root(int a)
{
if(node[a].root!=a)
return node[a].root = find_root(node[a].root);
return node[a].root;
}

void union_set(int a,int b)
{
a = find_root(a);
b = find_root(b);
if(a==b)//同一个根,说明是在同一个树下
return;
node[b].root=a;//把b的根赋为a的根,此时a已经是根,num==root
}

int main()
{
int n,m;
int i = 1;
bool flag=true;//true:是个树,false:不是树
init();
while(scanf("%d%d",&n,&m)!=EOF&&n>=0&&m>=0)
{
if(!flag&&n!=0&&n!=0)continue;//已经确定不是树了,就继续循环
if(n==0&&m==0)
{
int root_num=0;
for(int j = 1; j < max_num;j++)
{
//判断是否为森林,如果,root_num用来记录根的数目
if(node[j].num && find_root(j)==j)
root_num++;
if(node[j].conn>1)//如果出现某个节点的入度超过1,不是树
{
flag = false;
break;
}
}
if(root_num>1)//连通分支大于1,是森林不是树
flag=false;
if(flag)
printf("Case %d is a tree.\n",i++);
else printf("Case %d is not a tree.\n",i++);
flag = true;
init();
continue;
}
if((m!=n&&find_root(n)==find_root(m))||m==n)
flag = false;
else
{
//将m,n,记录为节点
node[m].num = 1;
node
.num = 1;
node[m].conn++;//入度增加一
union_set(n,m);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: