PAT chicken dish notes 1004 Counting Leaves

PAT chicken dish notes 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

important point:

This question should be examined traverse the level of the tree, then record each leaf node. Dish of chicken as I, at first completely thought up a queue to complete traverse the level, and then was surfing the big old show up, this question can use an array of structures to store the tree structure, then the queue is completed traverse the level, each access node on the child node of the deposit into the queue, the queue is empty has been circulating. Node subscript to keep children in the array.

#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;
}
Released five original articles · won praise 0 · Views 52

Guess you like

Origin blog.csdn.net/weixin_43842155/article/details/104408512