PAT A 1004. Counting Leaves (30)
来源:互联网 发布:怎么重新注册知乎 编辑:程序博客网 时间:2024/06/03 14:09
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 Input2 101 1 02Sample 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;}//结果
- PAT A 1004. Counting Leaves (30)
- PAT-A 1004. Counting Leaves (30) (树)
- PAT(A) 1004. Counting Leaves (30)
- PAT A 1004. Counting Leaves (30)
- PAT-A-1004. Counting Leaves (30)
- PAT (A )1004. Counting Leaves (30)
- PAT-A 1004. Counting Leaves (30)
- PAT-A 1004.Counting Leaves
- 1004. Counting Leaves (30)-PAT
- pat 1004. Counting Leaves (30)
- 【PAT】1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- pat 1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- PAT:1004. Counting Leaves (30)
- PAT 1004. Counting Leaves (30)
- [PAT]1004. Counting Leaves (30)
- javascript获取express传到jade的值
- 8集合类(Arraylist)
- 理解redis高可用方案
- Unit5 基本类型数据类型转换与字符串的使用
- CentOS7安装Couchbase
- PAT A 1004. Counting Leaves (30)
- Linux入门:权限管理之粘滞位
- 输入一个链表,反转链表后,输出链表的所有元素。就地逆转,头插法
- GDKOI2017 翻车记
- Java 读书笔记1
- 常见浏览器兼容性bug
- hdu 1280 前m大的数
- 剑指offer 复杂链表的复制
- Java例子:判断输入的年份是否为闰年