B. Christmas Spruce

Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn’t have children and has a parent.

Let’s call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it’s a spruce.

The definition of a rooted tree can be found here.

Input
The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i).

Vertex 1 is the root. It’s guaranteed that the root has at least 2 children.

Output
Print “Yes” if the tree is a spruce and “No” otherwise.

题意:

有一个树,如果每个非叶子节点节点包含的叶子节点不少于3,则输出Yes,否则输出No。

思路:

二维数组vector<int> vec[maxn]建图 保存它的每个孩子节点,判断孩子节点的度数是否为空 为空就是叶子节点 注意检查到一个节点的出度不大于3也不等于0就输出错误,因为它既不是叶子节点也不是包含3个叶子节点的节点

代码:

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

const int maxn = 1000+10;
vector< int > vec[maxn];

int main()
{
    int n;
    int tmp;
    cin>>n;
    for(int i=2;i<=n;i++)
    {
        cin>>tmp;
        vec[tmp].push_back(i);
    }
    bool flag=false;
    for(int i=1;i<=n;i++)
    {
        int count=0;
        int siz = vec[i].size();
       if(siz>=3)
       {
         for(int j=0;j<siz;j++)
         {
             if(!vec[vec[i][j]].size()) count++;
         }
         if(count<3) flag=true;
       }
       else if(siz!=0) flag=true;

       if(flag) break;
    }
    if(flag) printf("No\n");
    else printf("Yes\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/q451792269/article/details/80368874