您的位置:首页 > 其它

HDU 1325 Is It A Tree? 判断是否为一棵树

2014-05-06 13:55 525 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1325

POJ同题:http://poj.org/problem?id=1308

Is It A Tree?

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12963 Accepted Submission(s): 2919


Problem 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.

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 10010;
bool vis[maxn];
int indeg[maxn];
int main()
{
int cas = 0;
int a, b;
while(scanf("%d%d", &a, &b),a>=0||b>=0)
{
if(a==0 && b==0)
{
printf("Case %d is a tree.\n", ++cas);
continue;
}
int maxx = 0;
if(a > maxx) maxx = a;
if(b > maxx) maxx = b;
memset(vis, false, sizeof(vis));    //该结点是否存在
memset(indeg, 0, sizeof(indeg));
vis[a] = vis[b] = true;     //设置结点存在
indeg[b]++;                 //入度+1,注意是有顺序的
while(scanf("%d%d", &a, &b), a!=0||b!=0)
{
if(a > maxx) maxx = a;
if(b > maxx) maxx = b;
indeg[b]++;             //入度+1
vis[a] = vis[b] = true; //设置结点存在
}
bool flag = true;
int k = 0;
for(int i = 1; i <= maxx; i++)
if(vis[i] && indeg[i] > 1)    //入度大于1,说明一个结点有两个父结点,违背树的性质
{
flag = false;
break;
}
for(int i = 1; i <= maxx; i++)
if(vis[i] && indeg[i] == 0)     //入度等于0的点有两个以上(包括)的话,则说明根结点不唯一,可能是森林
k++;
if(!flag || k != 1)
printf("Case %d is not a tree.\n", ++cas);
else
printf("Case %d is a tree.\n", ++cas);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: