您的位置:首页 > 其它

POJ 1308 Is It A Tree?【裸的并查集】

2012-08-07 13:42 447 查看
Language:Default
Description

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>
#include<string.h>
#include<iostream>
using namespace std;
int f[1005], visit[1005], map[1005][1005];
int find(int x)
{
return x==f[x]?x:f[x]=find(f[x]);
}
int main()
{
int x, y, xx, yy, maxnum, i;
int cas=0;
while(1)
{
memset(visit, 0, sizeof(visit));
memset(map, 0, sizeof(map));
for(i=0; i<=1000; i++)
f[i]=i;
int flag=1;
maxnum=0;
while(1)
{
scanf("%d%d", &x, &y);
if(x==-1&&y==-1)    return 0;
if(x==0&&y==0)    break;
maxnum=max(maxnum, x); maxnum=max(maxnum, y);
xx=find(x), yy=find(y);
visit[x]=1, visit[y]=1;
if(yy!=y&&xx!=yy||x==y||map[x][y]==1||map[y][x]==1)//没有重复的 1 2 1 2;没有1 2 2 1; 没有多个父节点的
flag=0;
f[yy]=xx;
map[x][y]=1;
}
int num=0;
for(i=0; i<=maxnum; i++)
if(f[i]==i&&visit[i])
num++;
if(num>1)      flag=0;
cas++;
if(flag)
printf("Case %d is a tree.\n", cas);
else
printf("Case %d is not a tree.\n", cas);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: