【PAT甲级】1004 Counting Leaves (30 分) JS

最近疫情在家办公,足不出户,做做 PAT 的题。奉上【PAT甲级】JS 解题分析————第三篇。(1003 Emergency 暂时还不会,先跳过,哈哈)

原题

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. 输入的第一行,包含两个数字 N 和 M,N 是节点总数 0<N<100, M 非叶子节点的数量 <N
  2. 第一行后面有 M行,每行的格式为 ID K ID[1] ID[2] ... ID[K],其中 ID 是两位数字代表非叶子节点,K 是该节点的子节点数量,后面是子节点的 IDS。
  3. 为了简单,根节点 ID 定为 01。
  4. 如果输入 N 的值为 0, 不作处理。

输出说明:

  1. 对每个测试用例,你需要输出每个层级叶子节点的数量,以空格分割在一行输出。
  2. 举个简单的例子:树有2个节点,01 是根节点,02是它唯一的子节点。那么根节点这一级叶子节点数量为0,下一级叶子阶段数为1,输出0 1

简单来说,就是找出每层的叶子节点数。

解题

思路:

  • 思路一:深度优先遍历DFS,使用数组存储子节点,从上往下递归,到叶子节点结束,记录每层的叶子节点数量。
  • 思路二:广度优先遍历BFS,从根节点开始入队,队首节点出队,其子节点入队,统计叶子节点数量。

注意事项:

  1. 可能会碰到 1004 Counting Leaves 测试点4 结果为 答案错误 或 非零输入,原因是后面 M行的输入可能换行,在做字符串分割时需要用 string.split(/[\s\n]/)

测试用例:

  • input: “1”; output “1”
  • input: “2 1”, “01 1 02”; output: “0 1”
  • input: “3 2”, “01 1 02”, “02 1 03”; output: “0 0 1”
  • input: “15 9”, “01 2 02 03”, “02 3 04 05\n06”, “03 2 07 08”, “05 2 09 10”, “07 1 12”, “08 1 13”, “09 1 11”, “11 1 14”, “13 1 15”; output: “0 0 2 2 1 1”

代码:

const readline = require('readline');
rl = readline.createInterface({
   
  input: process.stdin,
  output: process.stdout
});

// 多行输入(行数视参数而定)
let K = -1; 
const inputs = [];
rl.on('line', function(data) {
   
  // 读取第一行的数据,获取 K-总行数的值
  if(K < 0) {
   
    const [N, M] = data.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值