1004 Counting Leaves(BFS)

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行,每行有一个ID K ID[1] ID[2] ... ID[K],id为这个非叶子节点的id,然后K为他的孩子数目,然后k个孩子的id,输入结束。输出:每一个辈分中有几个叶子节点。

光看这个,我们就想到BFS层次遍历寻找叶子节点,找出有多少辈分,然后输出各辈分的叶子节点。

#include<iostream>
#include<queue>
#include<bits/stdc++.h>
using namespace std;
const int maxn = 105;
struct node
{
	int level;
	int num;
	int child[maxn];
}dian[maxn];
int shu[maxn];

int solve()
{
	memset(shu, 0, sizeof(shu));
	queue<node>q;
	dian[1].level = 0;

	q.push(dian[1]);			//一开始根节点就是01 ,就是1
	int maxlevel=-1;

	while (!q.empty())
	{
		node t = q.front();
		q.pop();
		maxlevel = max(maxlevel, t.level);
		if (!t.num)
			++shu[t.level];
		else
		{
			for (int i = 0; i < t.num; i++)
			{
				dian[ t.child[i] ].level = t.level + 1;
				q.push( dian[t.child[i]] );
			}
		}
	}
	return maxlevel;
}


int main()
{
	int n, m;
	cin >> n >> m;
	int id, t;
	for (int i = 0; i < m; i++)
	{
		cin >> id >> t;
		dian[id].num = t;
		for (int j = 0; j < t; j++)
			cin >> dian[id].child[j];        //直接id 当作下标,直接将所有的节点都装进去了
										 //后面直接插入就行
	}
	int maxlevel = solve();
	for (int i = 0; i <= maxlevel; i++)
	{
		if (i)
			cout << ' ';
		cout << shu[i];

	}
	return 0;
}
发布了123 篇原创文章 · 获赞 83 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/tsam123/article/details/100766358