PAT 甲级 1004. Counting Leaves

来源:互联网 发布:淘宝耳机店推荐 编辑:程序博客网 时间:2024/06/06 05:37

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

  • Input

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

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 <iostream>#include <vector>#include <queue>using namespace std;const int MX = 100;int N, M;vector<int> children[MX];int leaf[MX] = {0};int layer;void Bfs(int root) {    queue<int> Q;   // 创建队列Q    Q.push(root);   // 根结点入队    int rootNode = root, new_rootNode;  // lastNode    layer = 1;  // 层数初始化为1    while (!Q.empty()) {    // 当队列不为空时循环        int t = Q.front();  // t是队头元素        Q.pop();    // 队头出队        if (children[t].size()) {   // 如果队头元素有孩子,即非叶子            for (int i = 0; i < children[t].size(); ++i) {                Q.push(children[t][i]); // 孩子入队            }            new_rootNode = children[t][children[t].size() - 1]; // 将入队的孩子看作根节点        } else {    // 如果队头元素没有孩子,就是叶子            leaf[layer]++;        }        if (t == rootNode) {    // 统计层数:rootNode只会更新为每层的第一个孩子            rootNode = new_rootNode;            ++layer;        }    }}int main(int argc, const char * argv[]) {    cin >> N >> M;    int father, k, child;    for (int i = 0; i < M; ++i) {        cin >> father >> k;        for (int j = 0; j < k; ++j) {            cin >> child;            children[father].push_back(child);        }    }    Bfs(1);    for (int i = 1; i < layer; ++i) {        if (i == 1)            printf("%d", leaf[i]);        else            printf(" %d", leaf[i]);    }    cout << endl;    return 0;}
原创粉丝点击