PAT (Advanced Level) 1004 Counting Leaves (30 分)
发布日期:2021-06-29 12:22:19 浏览次数:2 分类:技术文章

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

序:

又是一道30分的题,仔细一看,这是一道层次遍历多叉树的问题,用queue应该可以搞定。

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

Input Specification:

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.

The input ends with N being 0. That case must NOT be processed.

Output Specification:

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.找根,根节点是唯一一个不在儿子节点的节点,用一个数组进行0,1记录
2.存储,这里我用了一个map,把每个爸爸和对应的儿子序列对应
3.遍历,用queue遍历,一层层遍历。若遇到节点无儿子,cnt++;否则,将其儿子push进queue,等待下一层遍历

代码如下:

//层次遍历&队列//找根#include
using namespace std;int visit[110];unordered_map
> mp;int main(){
int n, m; scanf("%d%d", &n, &m); int father, k, temp; for(int i = 0; i < m; i++) {
scanf("%d%d", &father, &k); for(int j = 0; j < k; j++) {
scanf("%d", &temp); visit[temp] = 1; mp[father].push_back(temp); } } int root = 1; while(visit[root] != 0) root++; queue
qq; qq.push(root); int floor = 1; while(!qq.empty()) {
int len = qq.size(); int cnt = 0, ft; for(int i = 0; i < len; i++) {
ft = qq.front(); qq.pop(); if(mp[ft].size() == 0) cnt++; else {
for(int j = 0; j < mp[ft].size(); j++) qq.push(mp[ft][j]); } } if(floor == 1) printf("%d", cnt); else printf(" %d", cnt); floor++; } printf("\n"); return 0;}

总结:

1.queue中的front()是取队首元素,pop()踢掉队首元素
2.用floor作为表示,区分输出的空格
3.root应该从1开始遍历,因为题目中的节点序号对应
4.题目中说01固定为根,但我们给出的是通解。我们的解法可以适用不定根的情况。

转载地址:https://bridge-killer.blog.csdn.net/article/details/115416496 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:有将-输顿计算实例
下一篇:智能合约-投票合约测试

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月27日 07时29分13秒