PAT (Advanced Level) Practice 1004 Counting Leaves

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.

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

题目大意

有一个树,根结点编号为01,你需要找出每一层的叶子结点的个数。N是结点的个数,M是非叶子结点的个数。第一行数据是N和M,然后是M行数据,ID K ID[1] ID[2] … ID[K]表示编号为ID的结点有K个子节点,分别是ID[1] ID[2] … ID[K]。结点的编号是两位数。

题目分析

设ans[x]表示第x层的叶子结点的个数,num表示树的层数。
遍历每个结点,判断是否是叶子结点,然后求出它的层数,维护ans数组即可。求层数可以通过父结点一层一层的向上找。
结点的定义如下:

struct node
{
    vector<int> children;
    int father;
} p[105];

使用递归求层数

int f(int x)                 //返回p[x]所处的层数,设根结点层数为0
{
    if (x == 1)
        return 0;
    return f(p[x].father) + 1;
}

由于输出时需要输出每一层的叶子结点个数,但我们并不知道一共有多少层,所以在遍历结点的时候顺便维护一下树的层数num。
另外,N=1,M=0时需要进行特判。

AC代码

#include <bits/stdc++.h>
using namespace std;
struct node
{
    vector<int> children;
    int father;
} p[105];
int ans[105] = {0}, num = 0; //每一层的叶子结点的个数,num为最大层数的编号
int f(int x)                 //返回p[x]所处的层数,设根结点层数为0
{
    if (x == 1)
        return 0;
    return f(p[x].father) + 1;
}
int main()
{
    int n, m, i, k, id, id2;
    cin >> n >> m;
    if (n == 1 && m == 0) //特判
    {
        cout << 1 << endl;
        return 0;
    }
    while (m--)
    {
        cin >> id >> k;
        while (k--)
        {
            cin >> id2;
            p[id].children.push_back(id2);
            p[id2].father = id;
        }
    }
    for (i = 0; i < 105; i++)
    {
        if (!p[i].children.size() && p[i].father)
        {
            int l = f(i);
            num = max(num, l);
            ans[l]++;
        }
    }
    for (i = 0; i <= num; i++)
    {
        cout << ans[i];
        if (i != num)
            cout << " ";
    }
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部