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

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[101][101] = { -1 };//只会赋给第一个元素,别的默认为0
//fill(tree[0], tree[0] + 101*101, -1);
int leaf[101] = { 0 }; int step = 0; void dfs(int i, int depth){ if (tree[i][0] == -1){ leaf[depth]++; return; } int j = 0; while (tree[i][j] != -1){ dfs(tree[i][j], depth + 1); j++; } step = max(step, depth + 1); } int main(){ int n, m;
fill(tree[0], tree[0] + 101*101, -1); cin
>> n >> m; for (int i = 0; i < m; i++){ int root, num; cin >> root >> num; for (int j = 0; j < num; j++){ int leaf; cin >> leaf; tree[root][j] = leaf; } } int root = 1, depth = 0; dfs(root, depth); for (int i = 0; i <= step; i++){ if(i!=step)cout << leaf[i] << " "; else cout << leaf[i]; } system("pause"); }

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

---------------- 坚持每天学习一点点
原文地址:https://www.cnblogs.com/tccbj/p/10370467.html