博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT 解题报告 1004. Counting Leaves (30)
阅读量:6324 次
发布时间:2019-06-22

本文共 1977 字,大约阅读时间需要 6 分钟。

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

题目描述:

统计一颗树每一层的leaf数量。

算法分析:

思路1:BFS

本质就是lever order traversal, 可以用bfs遍历,然后每一层统计叶子数。

思路2:DFS

可以使用邻接矩阵的方式定义树结构。然后使用 dfs 遍历树的节点,并记录每层的叶子节点数量。 可以看到,时间空间的 trade-off 不仅仅是性能上的提升,也会影响带代码实现的复杂程度。

#include 
#include
#include
#include
#include
using namespace std;#define MX 101int mp[MX][MX];queue
que;int n,m;int bfs(int s) { int flag = 1; for (int i=1; i<=n; i++) { if (mp[s][i] == 1) { que.push(i); flag = 0; } } return flag;}void actbfs() { que.push(1); que.push(0); int cnt = 0; while (!que.empty()) { int s = que.front(); que.pop(); if (s == 0) { if (que.empty()) { printf("%d", cnt); break; } else { que.push(0); printf("%d ", cnt); cnt = 0; } } else { int flag = bfs(s); cnt += flag; } }}int main(){ scanf("%d%d", &n,&m); memset(mp, 0, sizeof(mp)); for (int i=0; i

 

 

 

转载地址:http://mqdaa.baihongyu.com/

你可能感兴趣的文章
创新还是真的丑?苹果这个设备等了三年终于更新
查看>>
Elasticsearch就这么简单
查看>>
Envoy 中的 xDS REST 和 gRPC 协议详解
查看>>
gfx-rs/hal跨平台图形抽象库使用介绍
查看>>
Hadoop老矣,为什么腾讯还要花精力在其开源发布上?
查看>>
IO流详解
查看>>
前端常见问题整理
查看>>
Android进程保活招数概览
查看>>
iOS拨打电话对话框问题解决
查看>>
Material过渡+Glide显示问题踩坑
查看>>
新浪微博API生成短链接
查看>>
c++ ignore
查看>>
如何解读决策树和随机森林的内部工作机制?
查看>>
别的设计师都下班撸串去了,你却还在右击另存为?
查看>>
使用Selenium+POI实现Excel自动化批量查单词
查看>>
0510 - 不贴标签,勿论长短
查看>>
java 源码分析 ---Byte
查看>>
PHP实现get/post请求中的注意点
查看>>
go开发属于自己的日志库-文件日志库实现
查看>>
Spring+SpringMVC+Mybatis框架整合步骤
查看>>