PAT A 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

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.

Output

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

 

就是求树的各层无子女节点数。

保存信息,bfs或dfs,把各层无子女节点数统计一下就行。

 

代码:

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

struct id_lv	//广度优先探测结构
{
	int id;		//id
	int level;	//所在层
};

int main()
{
	int n,m;
	int num_kid[100]={0};	//记录相应编号的节点的子女数
	vector<int> kid[100];	//记录相应编号节点的子女
	cin>>n>>m;	//n没有作用

	int i,j;
	int id,id1;
	for(i=0;i<m;i++)	//输入非叶节点信息
	{
		cin>>id;
		cin>>num_kid[id];
		for(j=0;j<num_kid[id];j++)
		{
			cin>>id1;
			kid[id].push_back(id1);
		}
	}

	int no_child[101]={0};	//记录各层的无子女节点数,层数从1开始计数
	int max_level=0;		//记录树的层数
	queue<id_lv> wf;		//用于广度优先探测
	id_lv tempi;	//预处理
	tempi.id=1;
	tempi.level=1;
	wf.push(tempi);
	while(!wf.empty())	//广度优先
	{
		if(num_kid[wf.front().id]!=0)	//节点有子女
			for(i=0;i<num_kid[wf.front().id];i++)
			{
				tempi.id=kid[wf.front().id][i];
				tempi.level=wf.front().level+1;
				wf.push(tempi);
				if(tempi.level>max_level)
					max_level=tempi.level;
			}
		else						//节点无子女
			no_child[wf.front().level]++;
		wf.pop();
	}

	cout<<no_child[1];	//输出
	for(i=2;i<=max_level;i++)
		cout<<" "<<no_child[i];

	return 0;
}


 

 

 

 

 

你可能感兴趣的:(C++,pat)