PAT 甲级 1004 Counting Leaves

https://pintia.cn/problem-sets/994805342720868352/problems/994805521431773184

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 0, the number of nodes in a tree, and M (<), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] ... ID[K]

where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.

The input ends with N being 0. That case must NOT be processed.

Output Specification:

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1leaf node. Then we should output 0 1 in a line.

Sample Input:

2 1
01 1 02

Sample Output:

0 1

代码:

#include <bits/stdc++.h>
using namespace std;

int N, M;
vector<int> v[110];
int vis[110];
int ans[110];
int deep = INT_MIN;

void dfs(int st, int depth) {
    if(v[st].size() == 0) {
        ans[depth] ++;
        deep = max(deep, depth);
    }

    for(int i = 0; i < v[st].size(); i ++)
        dfs(v[st][i], depth + 1);
}

int main() {
    scanf("%d%d", &N, &M);
    memset(vis, 0, sizeof(vis));
    while(M --) {
        int p, k;
        scanf("%d%d", &p, &k);
        for(int i = 0; i < k; i ++) {
            int c;
            scanf("%d", &c);
            vis[c] = 1;
            v[p].push_back(c);
        }
    }

    dfs(1, 0);
    printf("%d", ans[0]);
    for(int i = 1; i <= deep; i ++)
        printf(" %d", ans[i]);
    return 0;
}

  dfs 

原文地址:https://www.cnblogs.com/zlrrrr/p/10352680.html