0
点赞
收藏
分享

微信扫一扫

1004 Counting Leaves (30 分)

墨香子儿 2022-02-11 阅读 87

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

这一题求树叶子结点的个数
解释一下样例输入和输出
通过读题不难看出,这棵树只有两个节点1和2,根节点是1(题目有说),它的子节点是2,所以这棵树叶子结点只有一个就是2,根节点在第一层,它的叶子结点在第二层所以输出时
输出0和1(第一层叶子结点是0,第二层叶子结点有1个叶子结点)
参悟了前面几题有关树的题后,其实并不难

#include <iostream>
#include <vector>
using namespace std;
int n, m;
const int maxn = 110;
vector<int> child[maxn];
int ans[maxn];
int num = 0;
void DFS(int root, int depth)
{
	if (child[root].size() == 0)
	{
		num = max(num, depth);
		ans[depth]++;
		return;
	}
	for (int i = 0; i < child[root].size(); i++)
	{
		DFS(child[root][i], depth + 1);
	}
}

int main()
{
	int id, temp,k;
	cin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		cin >> id >> k;
		for (int j = 0; j < k; j++)
		{
			cin >> temp;
			child[id].push_back(temp);
		}
	}
	DFS(1, 1);
//	cout << num << endl;
	for (int i = 1; i <= num; i++)
	{
		cout << ans[i];
		if (i != num)
			cout << " ";
	}
	return 0;
}
举报

相关推荐

0 条评论