Is It A Tree?-题解

Is It A Tree?

https://ac.nowcoder.com/acm/problem/105905

题目描述
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.
思路:
是一棵树,所以只有根节点入度为0,其他节点入度都为1.

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <map>
using namespace std;
map<int,int>mp;
int a[1005],du[1005],fa[1005];
int main()
{
    for(int i=1;i;i++){
        mp.clear();
        memset(du,0,sizeof(du));
        int u,v,cnt=1,num=1;
        scanf("%d%d",&u,&v);
        if(u+v==-2)break;
        if(!mp[u])mp[u]=cnt++;
        if(!mp[v])mp[v]=cnt++;
        du[mp[v]]++;
        if(u==0){
            printf("Case %d is a tree.\n",i);
            continue;
        }
        while(scanf("%d%d",&u,&v),u+v){
            num++;
            if(!mp[u])mp[u]=cnt++;
            if(!mp[v])mp[v]=cnt++;
            du[mp[v]]++;

        }
        int flag=0;
        for(int j=1;j<cnt;j++){
            //printf("%d\n",du[j]);
            if(du[j]==0)flag++;
            if(du[j]>=2){
                flag=2;
                break;
            }
        }
        if(flag>=2||flag==0||cnt-2!=num){
            printf("Case %d is not a tree.\n",i);
        }else printf("Case %d is a tree.\n",i);
    }
    return 0;
}
全部评论

相关推荐

07-18 13:49
门头沟学院 Java
26小林不会梦到感谢...:这个点还在面暑期嘛不是马上开秋招了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务