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

提交代码


声明!是看了别人的方法,感觉不错,有所启发吐舌头

IDEA

1.考查树的存储与遍历,本题采用树的先根遍历

2.节点结构体的设计,存id,孩子的个数,用vector一次存孩子

3.遍历时的递归算法

4.注意传参时map<int,int> &m

5.map插入元素最简单的方法 m[1]=0;


CODE

#include<iostream>
#include<vector>
#include<map>
#define MAX_NUM 100
using namespace std;

struct Node{
	int id;                                                                              
	int children_num;
	vector<int> children;
};
int isExist(map<int,int> &m,int key){
	return (m.find(key)!=m.end());
}
void count_leaves(Node *tree,Node node,map<int,int> &result,int depth){
/*	if(result[depth]==0){
		result[depth]=0;
	}*/
	if(!isExist(result,depth)){
		result[depth]=0;
	}
	if(node.children_num==0){
		result[depth]++;
		return;
	}
	vector<int> children=node.children;
	for(int i=0;i<children.size();i++){
		count_leaves(tree,tree[children[i]],result,depth+1);
	}
}
int main(){
	int n,m;
	cin>>n>>m;
	Node tree[MAX_NUM];
	for(int i=0;i<MAX_NUM;i++){
		tree[i].id=0;
		tree[i].children_num=0;
	}
	for(int i=0;i<m;i++){
		int id,k;
		cin>>id>>k;
		tree[id].id=id;
		tree[id].children_num=k;
		for(int j=0;j<k;j++){
			int child;
			cin>>child;
			tree[id].children.push_back(child);
		}
	}
	map<int,int> result;
	count_leaves(tree,tree[1],result,1);
	map<int,int>::iterator it;
	for(it=result.begin();it!=result.end();it++){
		if(it==result.begin()){
			cout<<it->second;
		}else{
			cout<<" "<<it->second;
		}
	}
	
	return 0;
}




你可能感兴趣的:(pat,map应用,树的遍历,树的存储)