PAT菜鸡笔记1004 Counting Leaves

PAT菜鸡笔记1004 Counting Leaves

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

注意点:

本题考察的应该是树的层次遍历,然后记录下每层的叶子节点。菜鸡如我,一开始完全没想起来用队列完成层次遍历,然后就被网上冲浪的big old 秀到了,本题可以使用结构体数组存储树结构,然后用队列完成层次遍历,每访问一个节点就把节点的孩子存进队列,一直循环到队列为空。节点中存孩子在数组中的下标即可。

#include<iostream>
#include<queue>
#include<algorithm>
#include<stdio.h>

using namespace std;
const int Msize = 100;

struct node
{
	int children[Msize];
	int c_num = 0;
	int deepth;

}tree[Msize];
int leaves[Msize]={0};
int counting_leaves()
{
	queue<node> q;
	tree[1].deepth = 0;
	int Maxdeepth = -1;
	q.push(tree[1]);
	while (!q.empty())
	{
		node cur = q.front();
		q.pop();
		if (Maxdeepth < cur.deepth)
		{
			Maxdeepth = cur.deepth;
		}
		if (cur.c_num == 0)
		{
			leaves[cur.deepth]++;
		}
		else
		{
			for (int i = 0; i < cur.c_num; i++)
			{
				tree[cur.children[i]].deepth = cur.deepth + 1;
				q.push(tree[cur.children[i]]);
			}
		}
	}
	return Maxdeepth;
}
int main() {
	int N, M,k,num,deepth;
	cin >> N >> M;
	for (int i = 0; i < M; i++)
	{
		cin >> num >> k;
		tree[num].c_num = k;
		for (int j = 0; j < k; j++)
		{
			cin >> tree[num].children[j];
		}
	}
	deepth = counting_leaves();
	for (int i = 0; i <= deepth; i++)
	{
		cout << leaves[i] << (i == deepth ? "\n" : " ");
	}
	return 0;
}
发布了5 篇原创文章 · 获赞 0 · 访问量 52

猜你喜欢

转载自blog.csdn.net/weixin_43842155/article/details/104408512