最近疫情在家办公,足不出户,做做 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
原题翻译
一个家族的等级通常通过家谱的形式呈现。你的任务就是找出那些没有孩子的家族成员。
输入说明:
- 输入的第一行,包含两个数字 N 和 M,N 是节点总数
0<N<100
, M 非叶子节点的数量<N
。 - 第一行后面有 M行,每行的格式为
ID K ID[1] ID[2] ... ID[K]
,其中 ID 是两位数字代表非叶子节点,K 是该节点的子节点数量,后面是子节点的 IDS。 - 为了简单,根节点 ID 定为 01。
- 如果输入 N 的值为 0, 不作处理。
输出说明:
- 对每个测试用例,你需要输出每个层级叶子节点的数量,以空格分割在一行输出。
- 举个简单的例子:树有2个节点,01 是根节点,02是它唯一的子节点。那么根节点这一级叶子节点数量为0,下一级叶子阶段数为1,输出
0 1
。
简单来说,就是找出每层的叶子节点数。
解题
思路:
- 思路一:深度优先遍历DFS,使用数组存储子节点,从上往下递归,到叶子节点结束,记录每层的叶子节点数量。
- 思路二:广度优先遍历BFS,从根节点开始入队,队首节点出队,其子节点入队,统计叶子节点数量。
注意事项:
- 可能会碰到 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.