美文网首页
PAT 甲级 刷题日记|A 1004 Counting Lea

PAT 甲级 刷题日记|A 1004 Counting Lea

作者: 九除以三还是三哦 | 来源:发表于2021-08-21 08:41 被阅读0次

单词积累

hierarchy 层次 等级制度

pedigree 血统 家谱

sake 目的 利益

seniority level 资历 水平

题目

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<N<100, the number of nodes in a tree, and M (<N), 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 1 leaf 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;

const int maxn = 200;
int height[maxn];
int maxhei = 0;
struct node{
    int id;
    int height;
    vector<int> child;
}Node[maxn];

void bfs(int root) {
    queue<int> mq;
    mq.push(root);
    while (!mq.empty()) {
        int now = mq.front();
        if (Node[now].height > maxhei) maxhei = Node[now].height;
        if (Node[now].child.size() == 0) {
            int hei = Node[now].height;
            height[hei]++;
        }
        mq.pop();
        for (int i = 0; i < Node[now].child.size(); i++) {
            int t = Node[now].child[i];
            Node[t].height = Node[now].height + 1;
            mq.push(t);
        }
    }
}

int main() {
    int n, m;
    cin>>n>>m;
    int kids;
    int id;
    for (int i = 0; i < m; i++) {
        cin>>id>>kids;
        Node[id].id = id;
        Node[id].child.resize(kids);
        for (int j = 0; j < kids; j++) {
            cin>>Node[id].child[j];
        }
    }
    Node[1].height = 0;
    bfs(1);
    for (int i = 0; i <= maxhei; i++) {
        cout<<height[i];
        if (i != maxhei) cout<<" ";
        else cout<<endl;
    }
}

相关文章

网友评论

      本文标题:PAT 甲级 刷题日记|A 1004 Counting Lea

      本文链接:https://www.haomeiwen.com/subject/sufmbltx.html