1004 Counting Leaves (DFS)

题目描述

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

输入格式

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.

输出格式

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.

输入样例

2 1
01 1 02

输出样例

0 1

题目大意

给出结点数目n、非叶结点数目m、每个非叶结点的孩子数num及所有孩子的下标child[i],求出每个level对应的叶结点数目。

思路

本题关键在于用DFS求出每个结点的层次level,同时判断该结点是否为叶结点,若为叶结点,则更新相应level的leaf数目。

AC代码

#include <iostream>
#include <algorithm>
using namespace std;

struct node{
	bool flag = false; //以该下标为id的结点是否存在 
	int level;
	int num = 0; //孩子数量默认为0 
	int child[110]; //孩子下标 
}Tree[110], Node;
int n, m; //结点数 非叶结点数
int depth = 0, leaf[110] = {0}; //每层叶结点数 

//计算每个结点的level,并更新相应叶结点数 
void getlevel(int id, int level){ 
	if(Tree[id].flag == false) return;
	Tree[id].level = level;
	depth = max(depth, level);
	if(Tree[id].num == 0)
		leaf[level]++;
	for(int i = 0; i < Tree[id].num; i++)
		getlevel(Tree[id].child[i], level + 1);
}

int main(){
	cin>>n>>m;
	int id, cnt, c;
	Tree[1].flag = true;
	for(int i = 0; i < m; i++){
		cin>>id>>cnt;
		Tree[id].num = cnt;
		for(int j = 0; j < cnt; j++){
			cin>>c;
			Tree[id].child[j] = c;
			Tree[c].flag = true;
		}
	}
	getlevel(1, 1);
	if(n == 1) //只有根结点
		cout<<"1"; 
	else{
		cout<<"0"; //第一层无叶结点 
		for(int i = 2; i <= depth; i++)
			cout<<" "<<leaf[i];		
	}
	return 0;
}

在这里插入图片描述

发布了9 篇原创文章 · 获赞 0 · 访问量 79

猜你喜欢

转载自blog.csdn.net/qq_43072010/article/details/104796900
今日推荐