一、题目
1004 Counting Leaves(30 分)
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
二、题目大意
给一个树,求每一层叶子节点的个数
三、考点
树、DFS
四、解题思路
1、使用邻接矩阵保存树的结构,将每个儿子节点保存到父节点的 vector 中,使用 int 数组 level_num 保存每一层叶节点的个数;
2、DFS搜索, dfs(int index,int level) 维护当前节点和层数两个变量;
3、DFS中遍历下一层的时候,需要注意当前节点的数字不是 i ,而是 vec[index][i]。这里是使用邻接矩阵,如果直接使用二维数组的话,思路简单些,但占用内存会增加;
4、在输出的过程中,level_num为 0 的情况下也要输出,而最大层数也不知道,所以要有一个全局变量 max_level 维护最大层数。
【注意】数据保存在二维数组、邻接矩阵、链表中遍历的方式有些不同,不要混淆。
五、代码
#include<iostream>
#include<vector>
#define N 110
using namespace std;
vector<int> vec[N];
int n, m;
int level_num[N] = {0};
bool visit[N] = { false };
int max_level = 0;
void dfs(int index,int level) {
//更新最大值
if (max_level < level)
max_level = level;
//终止条件
if (vec[index].size() == 0) {
level_num[level]++;
}
//下一层
for (int i = 0; i < vec[index].size(); ++i) {
int now_index = vec[index][i];
if (visit[now_index] == false) {
visit[now_index] = true;
dfs(now_index, level + 1);
}
}
}
int main() {
//输入
cin >> n >> m;
while (m--) {
int id, k,a;
cin >> id >> k;
while (k--) {
cin >> a;
vec[id].push_back(a);
}
}
//n==0特殊情况处理
if (n == 0)
return 0;
//DFS
visit[1] = true;
dfs(1,0);
//输出
for (int i = 0; i <= max_level; ++i) {
if (i != 0)
cout << " ";
cout << level_num[i];
}
system("pause");
return 0;
}