PAT A 1004. Counting Leaves (30)

来源:互联网 发布:怎么重新注册知乎 编辑:程序博客网 时间:2024/06/03 14:09
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 101 1 02
Sample Output
0 1
//题目分析:
用vector存储数量可变的子节点;
最后要求按层输出叶子结点的个数;
vector assign 方法:vector<int> v; v.assign(n,t);//==>将n个t重新赋值给vector,可用于初始化
//代码
#include <iostream>#include <vector>using namespace std;struct Node{int id;int level;int k;vector<int> child;};Node nodes[100];int maxLevel=0;vector<int> levels;void setLevel(int id,int level){nodes[id].level=level;if(maxLevel<level)maxLevel=level;if(nodes[id].child.empty()){return;}for(int i=0;i<nodes[id].k;i++){setLevel(nodes[id].child[i],level+1);}return;}void getLevels(int id){if(nodes[id].child.empty()){levels[nodes[id].level]++;return;}for(int i=0;i<nodes[id].k;i++){getLevels(nodes[id].child[i]);}return;}int main(){int N,M;cin>>N>>M;for(int i=0;i<M;i++){int K,id;scanf("%d%d",&id,&K);nodes[id].id=id;nodes[id].k=K;nodes[id].child.resize(K);for(int k=0;k<K;k++){scanf("%d",&nodes[id].child[k]);}}setLevel(1,0);levels.assign(maxLevel+1,0);getLevels(1);for(int i=0;i<levels.size()-1;i++){cout<<levels[i]<<' ';}cout<<levels[levels.size()-1]<<endl;;system("pause");return 0;}
//结果
0 0
原创粉丝点击