PAT 1004. Counting Leaves (30)(BFS)

来源:互联网 发布:上海笕尚服饰淘宝店 编辑:程序博客网 时间:2024/06/08 06:07

题目

1004. Counting Leaves (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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

解题思路

  • 1.统计每层没有孩子的人的个数然后输出即可。

AC代码

#include<iostream>#include<vector>#include<deque>#include<map>#include<cstdio>using namespace std;map<int,vector<int> > family;int main(int argc, char *argv[]){    int n,m;    scanf("%d %d",&n,&m);    int father,numOfChildren,children;    for (int i = 0; i < m; ++i) {        scanf("%d %d",&father,&numOfChildren);        for (int j = 0; j < numOfChildren; ++j) {            scanf("%d",&children);            family[father].push_back(children);        }    }    deque<int> nextmember;    vector<int> numOfEveryLever;    nextmember.push_back(01);    while (!nextmember.empty()) {        //计算该层的member个数        int now_top,now_total,cnt = 0;        //用now记录当前的层并清空下一层        deque<int> now = nextmember;        nextmember.clear();        while (!now.empty()) {            now_top = now.front();            now_total = now.size();            if (family[now_top].empty()) {                cnt++;            }else {                //非空则将他的孩子放入nextmember里面                for (int i = 0; i < family[now_top].size(); ++i) {                    nextmember.push_back(family[now_top][i]);                }            }            now.pop_front();        }        //将cnt记录到numOfeveryLevr里面        numOfEveryLever.push_back(cnt);    }    printf("%d",numOfEveryLever[0]);    for (int i =1 ; i < numOfEveryLever.size() ; ++i) {        printf(" %d",numOfEveryLever[i]);    }    printf("\n");    return 0;}
0 0