1004. Counting Leaves (30)

来源:互联网 发布:python 面部表情识别 编辑:程序博客网 时间:2024/05/16 11:47

1004. Counting Leaves (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 101 1 02
Sample Output

0 1

#include<iostream>#include<string>#include<algorithm>#include<sstream>using namespace std;class family {          //采用父亲兄弟的模式public:int ID;family* next_brother=NULL;family* first_child=NULL;};int levelmax = 0;int leaf_count[101] = { 0 };void find_leaf_node(family* a,int level) {//递归方式获得叶节点数量family* b;while (a!= NULL) {if (a->first_child == NULL)leaf_count[level]++;else {b = a->first_child;find_leaf_node(b, level + 1);}a = a->next_brother;if (level > levelmax)levelmax = level;//找到树的深度}}int main() {int N,M;int i,temp0,temp1,temp2=-1,j,k;cin >> N>>M;family *person = new family[N+1];for (i = 0; i < M; i++) {//建树,这里用的是先建立数组,也就是不用动态分配内存cin >> temp0;cin >> j;temp2 = -1;for (k = 0; k < j; k++) {cin >> temp1;if (temp2 == -1)person[temp0].first_child = &person[temp1];elseperson[temp2].next_brother = &person[temp1];temp2 = temp1;}}find_leaf_node(&person[1], 1);//cout << "levelmax->"<<levelmax << ":" << endl;for (i = 1; i < levelmax+1; i++) {cout <<leaf_count[i] ;if (i != levelmax)cout << " ";}}
感想:简单的题目,无需赘言,不会做说明基础没打好,再回去看看数据结构的书

1 0
原创粉丝点击