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

AC参考代码:
#include <iostream>
#include <vector>
#include <map>
#include <fstream>

using namespace std;
map< int,vector<int> > myTree;	//用链式结构来实现多叉树的数据结构

int leafRecord[101] = {0};			//用record数组来实现每一层叶子结点的计数 

void DFS(int start,int level)
{
	if(myTree[start].empty()){		//临界情况判断 
		leafRecord[level]++;
		return;
	}
	vector<int>::iterator ite;		//用迭代期 遍历子节点 
	for(ite=myTree[start].begin();ite!=myTree[start].end();ite++){
		DFS(*ite,level+1);
	}
} 

int main()
{
	//ifstream cin("1.txt");
	int N,M,head,num,index,leafNum;
	cin>>N>>M;
	leafNum = N-M;
	for(int i=0;i<M;i++){
		cin>>head>>num;
		for(int j=0;j<num;j++){
			cin>>index;
			myTree[head].push_back(index);
		}
	}
	DFS(1,0);
	int leafCnt = leafRecord[0];
	//cout<<leafCnt<<endl;
	for(int i=1;leafCnt<=leafNum;i++){
		leafCnt!=leafNum?printf("%d ",leafRecord[i-1]):printf("%d",leafRecord[i-1]);
		if(leafCnt == leafNum) break;		//这边需对边界进行判断退出 
		leafCnt += leafRecord[i];
	}
	return 0;
}


本题主要是利用深度遍历实现每个层次上的叶子节点的计数;
这边利用map+vector实现多叉树的链式数据结构
题目中的隐含条件leafRecord中的节点数刚好等于N-M实现最后的遍历

水水过了!!

你可能感兴趣的:(数据结构,C++)