链接:https://ac.nowcoder.com/acm/problem/105905
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 10000K,其他语言20000K
64bit IO Format: %lld
题目描述
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.
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.
输入描述:
The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero.
输出描述:
For each test case display the line “Case k is a tree.” or the line “Case k is not a tree.”, where k corresponds to the test case number (they are sequentially numbered starting with 1).
示例1
输入
复制
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
输出
复制
Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree
题解:
题意:判断给的是不是树
我们想想树的性质,每个点都有一个父亲节点,除了根节点
前者我们可以用并查集维护,后者可以用入度出度来判断,因为根节点只有出度,入度为0,而其他点的入度为1
为了避免是森林,我们还应该要求所有点必须联通
对了,空树也为树
代码:
/*1.无环; 2.除了根,所有的入度为1,根入度为0; 3.只有一个根,不然是森林了。再注意这里空树也是树。 */
#include<bits/stdc++.h>
using namespace std;
const int maxn=100006;
int dp[mxan];
//我们可以用dp[1]表示父节点,dp[2]表示子节点,来标记各个点
int main()
{
int a,b,flag,edge,node;
int t=1;
while(1)
{
node=0;//结点数
edge=0;//边数
flag=0;
memset(dp,0,sizeof(dp));
while(~scanf("%d %d",&a,&b)&&a&&b)
{
if(a<0||b<0)
return 0;//a和b为负数时,结束程序
if(dp[b]==2)//b结点已经做过子节点
flag=1;
//如果b已经作为过子节点,再一次做子节点,说明出现两个父节点(也可能是重复的边,也不是树),不是树
if(dp[a]==0)
node++;
if(dp[b]==0)
node++;
dp[a]=1;
dp[b]=2;
edge++;
}
if(flag==0&&node==edge+1)
//所有点连通&&节点数=边数+1
printf("Case %d is a tree.\n",t++);
else
printf("Case %d is not a tree.\n",t++);
}
return 0;
}