Description
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.
In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.
Input
Output
Sample Input
6 8 5 3 5 2 6 4
5 6 0 0 8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0 3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1
Sample Output
Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.
跟小希的迷宫差不多,需要注意的是小希的迷宫是无向图,而本题是有向图。
判断是不是一棵树需要的条件如下:
1. 肯定满足只有一个树根,只有一个入度为0的点。
2. 除了根每个点的入度只能为1
3. 无环
4. n个点只能有n-1个边
直接从小希的迷宫进行改的,不过本代码在poj AC ,但是HDU Wrong Answer
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int set[];
bool vis[];
bool flag;
int find(int x)
{
return set[x]==x?x:set[x]=find(set[x]);
}
int main()
{
int a,b,k=;
while(scanf("%d%d",&a,&b))
{
int maxn=-;
if(a<&&b<)
break;
flag=true;
if(a==&&b==)
{
printf("Case %d is a tree.\n",++k);
continue;
}
for(int i=; i<; i++)
{
set[i]=i;
vis[i]=false;
}
while(a||b)
{
maxn=max(maxn,max(a,b));
vis[a]=true,vis[b]=true;
int x=find(a);
int y=find(b);
if(x!=y)
{
// if(x<y)
set[x]=y;
//else
//set[y]=x;
}
else
flag=false;
scanf("%d%d",&a,&b);
}
int ans=;
for(int i=; i<=maxn; i++)
{
if(vis[i] && set[i]==i)
ans++;
if(ans>)
flag=false;
}
if(flag)
printf("Case %d is a tree.\n",++k);
else
printf("Case %d is not a tree.\n",++k);
}
return ;
}