1004 Counting Leaves (30分)【BFS,DFS,树的层序遍历】
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
题目大意:
第一行输入告诉你拥有的家庭成员数量n以及非叶子结点数m。接下来是m行,每一行首先输入一个非叶子结点的编号,随后是整数k告诉你该结点拥有k个子结点,接着输入该结点的子节点编号。题目要求你输出各层的非叶子结点个数。
解题思路:
很明显,这道题用到的数据结构是树!
考虑到要我们输出各层的非叶子结点数,我们可以用bfs。首先用一个leaf数组来统计各层的叶子结点数 ,我们从01编号的根节点开始递归,如果当前结点的子结点数为0(即不存在以该结点为起始点的边,这里我用了链式前向星建树,因此条件为head[u]==-1),则当前层的叶子结点数加1;否则遍历以该结点的所有能到的点。
#include<iostream>
using namespace std;
struct Node {
int to;
int next;
}edge[110];
int head[110];
int cnt = 0;
void add(int u, int v)
{
edge[cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt++;
}
int leaf[110] = { 0 };
int maxlevel = 0;
void bfs(int u,int level)
{
if (head[u] == -1)
{
leaf[level]++;
if (level > maxlevel)
maxlevel = level;
}
else {
for (int i = head[u]; ~i; i = edge[i].next)
{
bfs(edge[i].to, level+1);
}
}
}
int main()
{
int n, m;
cin >> n >> m;
fill(head, head + n+1, -1);
for (int i = 0; i < m; i++)
{
int u,t;
cin >> u >> t;
while (t--)
{
int v;
cin >> v;
add(u, v);
}
}
bfs(1,0);
for (int i = 0; i <= maxlevel; i++)
{
cout << leaf[i];
if (i == maxlevel)
cout << endl;
else cout << " ";
}
return 0;
}

浙公网安备 33010602011771号