pat 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, 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
 题目大意: 求每一层上的叶子结点个数。 思路: 用bfs 代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#define MaxSize 105
using namespace std;
struct Node
{
    int k;
    int leaf[MaxSize];
};
int layer;
int leafCount[MaxSize];
Node *nodes[MaxSize];
void bfs()
{
    int seq[MaxSize];
    int front = 0, end = 0;
    int k, l; //当前层和下一层的结点个数
    Node *t;
    layer = 0;
    seq[end] = 1;
    end = (end + 1) % MaxSize;
    k = 1;
    l = 0;
    while (front != end)
    {
        t = nodes[seq[front]];
        front = (front + 1) % MaxSize;
        if (t->k == 0)
        {
            leafCount[layer]++;
        }
        else
        {
            l += t->k;
            for (int i = 0; i < t->k; i++)
            {
                seq[end] = t->leaf[i];
                end = (end + 1) % MaxSize;
            }
        }
        k--;
        if (k == 0)
        {
            layer++;
            k = l;
            l = 0;
        }
    }
}
int main()
{
    memset(leafCount, 0, sizeof(leafCount));
    for (int i = 0; i < MaxSize; i++)
    {
        nodes[i] = new Node();
        nodes[i]->k = 0;
    }
    int n, m, k;
    int num;
    cin >> n >> m;
    if (n == 0)
        return 0;
    Node *n1;
    for (int i = 0; i < m; i++)
    {
        cin >> num >> k;
        n1 = nodes[num];
        n1->k = k;
        for (int j = 0; j < n1->k; ++j)
        {
            cin >> n1->leaf[j];
        }
    }
    bfs();
    for (int i = 0; i < layer; i++)
    {
        if (i != 0)
            cout << " " << leafCount[i];
        else
            cout << leafCount[i];
    }
    return 0;
}

感想:

一开始初始化指针数组为NULL,然后输入的时候新建,可能哪个结点输入的时候没建,导致两个样例过不去。dfs的代码写起来好少。

上一篇:数据结构之线性表1


下一篇:#洛谷模拟系列#