1004 Counting Leaves (30 分)

Posted abszse

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1004 Counting Leaves (30 分)相关的知识,希望对你有一定的参考价值。

题目链接:

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 1 leaf node. Then we should output 0 1 in a line.

Sample Input:

2 1
01 1 02

Sample Output:

0 1

题目大意:

一个树,求其每层的叶子结点个数。

思路:

1、通过结构体存储树,将父节点记录。

2、知道了自己的父亲结点的同时也知道了自己的层数(父节点层数+1)。

3、自己是否有孩子结点在输入的时候就可以进行记录(ID即为非叶节点)。

注意事项:

1、输入并非有序,先把所有结点的父节点记录下来,不要直接记录层数,因为可能父节点还没有读取到,就会导致没有层数。

2、当只有一个根时,输出1,根也是一个结点(好吧,是我的树知识不过关~-~)

AC代码:

技术图片
#include <iostream>
#include <cstring>

using namespace std;

struct
{
    int childHave = 0;    //是否为叶子节点
    int level;            //层数
    int father;           //父节点
}root[105];

int sum[105];

int main()
{
    memset(sum,0,sizeof(sum));
    int n,m;
    cin >> n >> m;          //记录数据
    root[1].level = 1;
    for(int i=1;i<=m;i++)
    {
        int r,k;
        cin >> r >> k;
        root[r].childHave = 1;
        for(int j=1;j<=k;j++)
        {
            int temp;
            cin >> temp;
            root[temp].father = r;
        }
    }
    int maxa = 0;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(root[j].father == i) root[j].level = root[i].level+1;        //如果父亲节点为i则层数为i层数+1
            if(root[j].level > maxa) maxa = root[j].level;                  //更新最大层数
        }
    }
    for(int i=1;i<=n;i++) if(root[i].childHave == 0) sum[root[i].level]++;
    cout << sum[1];
    for(int i=2;i<=maxa;i++) cout <<   << sum[i];
    return 0;
}
View Code

 

以上是关于1004 Counting Leaves (30 分)的主要内容,如果未能解决你的问题,请参考以下文章

1004 Counting Leaves (30 分)

1004. Counting Leaves (30)

1004. Counting Leaves (30)

1004. Counting Leaves (30)

1004 Counting Leaves (30)

PAT 1004 Counting Leaves (30分)