[PAT brush questions] 1476. Counting leaf nodes

topic

Family relationships can be represented by a family tree, given a family tree, your task is to find out which members do not have children in it.
input format

The first line contains an integer N
representing the total number of nodes in the tree and an integer M

Indicates the number of non-leaf nodes.

Next M

lines, each in the format:

ID K ID[1] ID[2] … ID[K]

ID
is a two-digit number, indicating a non-leaf node number, K is an integer, indicating the number of its child nodes, the next K ID[i]

It is also a two-digit number, indicating the number of a child node.

For simplicity, we fixed the root node to 01

The numbers of all nodes are 01,02,03,…,31,32,33,…,N

.
output format

The output starts from the root node, from top to bottom, how many leaf nodes each level of the tree contains.

The output is on one line, and the integers are separated by spaces.
data range

0<N<100

Input sample:

2 1
01 1 02

Sample output:

0 1

Example explanation

This example represents a tree with only 2
nodes, where 01 is the root and 02

A node is its only child node.

Therefore, at the root level, there are 0
leaf nodes; at the next level, there are 1

a leaf node.

So, we should output 0 1 in one line.

ideas

Brute force search + storage method of adjacency list
[Acwing algorithm foundation] 3.1 dfs
[Acwing algorithm foundation 3.3 Number and graph storage]

C++ code

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 110;
int n, m;
int h[N], e[N], ne[N], idx;

int cnt[N], max_depth;  // 保存每一层叶子节点的数量

// 添加一条a连向b的边
void add(int a, int b)
{
    
    
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void dfs(int u, int depth)
{
    
    
    if (h[u] == -1)  // 说明它是叶子节点
    {
    
    
        cnt[depth]++;
        max_depth = max(max_depth, depth);
        return;
    }

    for (int i = h[u]; ~i; i = ne[i])
        dfs(e[i], depth + 1);
}

int main()
{
    
    
    cin >> n >> m;

    memset(h, -1, sizeof h);
    for (int i = 0; i < m; i++)
    {
    
    
        int id, k;
        cin >> id >> k;
        while (k--)
        {
    
    
            int son;
            cin >> son;
            add(id, son);
        }
    }

    dfs(1, 0);  // 从1号点开始暴搜

    cout << cnt[0];
    for (int i = 1; i <= max_depth; i++)
        cout << ' ' << cnt[i];
    cout << endl;

    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326171026&siteId=291194637