1004. Counting Leaves (30)
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 Input2 1 01 1 02Sample 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];
else
person[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 << " ";
}
}
感想:简单的题目,无需赘言,不会做说明基础没打好,再回去看看数据结构的书