codeforces - 913B Christmas Spruce(树)

题目链接:https://vjudge.net/problem/CodeForces-913B

大概题意就是给你一颗有根数,如果每个中间结点(或者根结点)的叶的数量大于等于3就是云杉,否则不是。

我们可以递归的进行判断:

1.某结点是否有3个以上的叶结点

2.某结点的非叶结点是否有3个以上的叶结点

#include<set>
#include<map>
#include<stack>
#include<queue>
#include<cmath>
#include<stdio.h>
#include<cctype>
#include<string>
#include<vector>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define endl '\n'
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
#define mst(a) memset(a, 0, sizeof(a))
#define _test printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const double pi = acos(-1.0);
const double eps = 1e-7;
const int INF = 0x3f3f3f3f;
const int _NAN = -0x3f3f3f3f;
const int NIL = -1;
const int maxn = 1e3+10;
struct node {
    int p, l, r;
};
vector<int> trees[maxn];
bool solve(int root) {
    int cnt = 0;
    for (int i = 0; i<trees[root].size(); ++i)
        if (trees[trees[root][i]].empty())
            ++cnt;
    if (cnt < 3)
        return false;
    else {
        for (int i = 0; i<trees[root].size(); ++i)
            if (!trees[trees[root][i]].empty())
                //solve(trees[root][i]); 错误1:更深一步的递归不影响之前的结果
                //return solve(trees[root][i]); 错误2:如果第一次递归是true即使后面是false也不影响
                if (!solve(trees[root][i])) 
                    return false;
    }
    return true;
}
int main(void) {
    int n;
    while(~scanf("%d", &n)) {
        for (int i = 2, node; i<=n; ++i) {
            scanf("%d", &node);
            trees[node].push_back(i);
        }
        printf(solve(1) ? "Yes\n" : "No\n");
        for (int i = 0; i<maxn; ++i)
            trees[i].clear();
    }
    return 0;
}

 

posted @ 2020-01-30 10:57  shuitiangong  阅读(181)  评论(0编辑  收藏  举报