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

题目大意:求解树中叶子节点的个数,并将每层叶子节点个数输出。
解题时将树存储为临接表,然后遍历深搜一遍,记录下每层的叶子节点个数即可求解。

#include<iostream>
#include<stdio.h>
#include<queue>
#include<cstring>
#include<algorithm>
#include<stack>
#include<map>
#include<vector>
using namespace std;
#define max 102
map<int,vector<int> >tree;//临接表存储树信息 
int N,M,K;
int num_leaf_level[max];  //记录每层叶子节点的个数 
void DFS(int level, int root){
	if(tree[root].empty()){ //临接表为空,即root为叶子节点,在level层的叶子计数中加1; 
		num_leaf_level[level]++;
		return;
	}
	//int number = tree[root]
	vector<int>child(tree[root]);
	int count = child.size();
	//cout<<count<<endl;
	for(int i = 0;i<count;i++){
		DFS(level+1,child[i]);
	}
}
int main(){
	memset(num_leaf_level,0,sizeof(num_leaf_level));
	scanf("%d%d",&N,&M);
	int i,j,root,child_num,child;
	for(i=0;i<M;i++){
		scanf("%d",&root);
		scanf("%d",&child_num);
		for(j=0;j<child_num;j++){
			scanf("%d",&child);
			tree[root].push_back(child);
		}
	}
	DFS(0,1);//第0层,根节点为01 
	int leaf_num = N-M;
	int num = num_leaf_level[0];
	printf("%d",num);
	for(i=1;num<leaf_num;i++){
		printf(" %d",num_leaf_level[i]);
		num+=num_leaf_level[i];
	}
	printf("
");
	return 0;
}

  

原文地址:https://www.cnblogs.com/grglym/p/7654666.html