1004. Counting Leaves (30)
题目地址: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.
- 输入格式:
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. - 输出格式:
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.
解题方法:
这题我一开始选用的是用孩子兄弟表示法构造树,然后后来发现出现了两个段错误,猜想估计测试样例在输入的时候并非按正常的输入方法输入(即父节点是还未经出现过的,当然可能也是我逻辑问题),于是就是参考了柳婼 の blog的程序,改成了bfs。
这里主要是用一个Level数组和LeafNum数组来记录层数和每层叶子结点数,很巧妙。
可以在LeafNum数组中传入Level的值(用来记录当前结点的层高)作为下标,再依靠孩子结点的层高为双亲结点的层高+1,这样就解决了层序遍历的问题。
程序:
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
int Level[101] = {0};
int LeafNum[101] = {0};
vector <int> v[101];
int MaxLevel = 0;
void bfs()
{
queue <int> Q;
Q.push(1);
while (!Q.empty())
{ /* 如果队列不空 */
int node = Q.front();
Q.pop();
if (Level[node] > MaxLevel)
MaxLevel = Level[node]; /* 计算最大层次数 方便后面遍历 */
if (v[node].size() == 0)
LeafNum[Level[node]]++; /* 如果该结点没孩子,那么该高度的叶子结点数++ */
else
{ /* 如果该结点有孩子 */
for (int i = 0; i < v[node].size(); i++)
{
Q.push(v[node][i]);
Level[v[node][i]] = Level[node] + 1; /* 孩子的层次比父亲高一级 */
}
}
}
}
int main(int argc, char const *argv[])
{
int N, M, K, node, child;
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++)
{
scanf("%d %d", &node, &K);
for (int j = 0; j < K; j++)
{
scanf("%d", &child);
v[node].push_back(child);
}
}
bfs();
printf("%d", LeafNum[0]);
for (int i = 1; i <= MaxLevel; i++)
printf(" %d", LeafNum[i]);
return 0;
}