#13130. 珅泽教育CSP-J第一轮模拟考第二十九套 第 31 题

珅泽教育CSP-J第一轮模拟考第二十九套 第 31 题

二、程序阅读题(第 16—18 大题,共 18 个小题,40 分)

程序阅读(判断是否可选根成为完整二叉树)

输入不超过 10^6 的正整数 n,随后输入 n-1 条边构建一棵树。保证存在某个点作为根后,每个点的子结点数量不超过 2。

#include <iostream>
#include <vector>
using namespace std;
vector<int> edge[1000005];
int max_depth;
void f(int now, int fa, int depth) {
    max_depth = max(max_depth, depth);
    for (int i = 0; i < edge[now].size(); i++) {
        if (edge[now][i] == fa)
            continue;
        f(edge[now][i], now, depth + 1);
    }
    return;
}
int main() {
    int n;
    cin >> n;
    int t = n;
    while (--t) {
        int u, v;
        cin >> u >> v;
        edge[u].emplace_back(v);
        edge[v].emplace_back(u);
    }
    int star = 0, num = 0;
    for (int i = 1; i <= n; i++) {
        if (edge[i].size() == 2) {
            star = i;
            num++;
        }
    }
    if (num == 1) {
        f(star, 0, 1);
        cout << "yes " << max_depth;
    } else
        cout << "no";
    return 0;
}

下列哪组输入能输出 yes(每组首数为 n,后面为 n-1 条边的端点序列)?

{{ select(1) }}

  • 11 4 1 9 3 6 7 5 10 2 8 2 5 5 11 1 9 1 6 4 2
  • 8 6 3 7 5 8 6 6 2 7 4 3 1 8 7
  • 6 1 2 2 3 3 4 4 5 5 6
  • 5 1 2 3 4 1 3 3 5