PAT A1004 Counting Leaves (30 分)——树,DFS,BFS

时间:2023-01-20 17:26:59

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, the number of nodes in a tree, and M (<), 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 01level, 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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#include <iostream>
using namespace std;
int tree[][] = { -1 };//只会赋给第一个元素,别的默认为0
//fill(tree[0], tree[0] + 101*101, -1);
int leaf[] = { };
int step = ;
void dfs(int i, int depth){
if (tree[i][] == -1){
leaf[depth]++;
return;
}
int j = ;
while (tree[i][j] != -1){
dfs(tree[i][j], depth + );
j++;
}
step = max(step, depth + );
}
int main(){
int n, m;
fill(tree[0], tree[0] + 101*101, -1);
cin >> n >> m;
for (int i = ; i < m; i++){
int root, num;
cin >> root >> num;
for (int j = ; j < num; j++){
int leaf;
cin >> leaf;
tree[root][j] = leaf;
}
}
int root = , depth = ;
dfs(root, depth);
for (int i = ; i <= step; i++){
if(i!=step)cout << leaf[i] << " ";
else cout << leaf[i];
}
system("pause");
}

注意点:一开始题目都没看懂,给的例子太不具代表性了,读了好多遍终于知道是要求每层的叶节点个数并输出。就是考了一个深度优先搜索(DFS),居然还不会做,DFS要用递归一层层遍历,遍历完要记录最深到几层了,方便后面输出。这里建树用了二维数组,其实有点蠢,用vector数组会方便一点。另外,二维数组的初始化只能用fill或memset,直接像一维数组那样给一个值只会赋给数组第一个元素。