1004 Counting Leaves
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 0, the number of nodes in a tree, and M (<), 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
.
The input ends with N being 0. That case must NOT be processed.
Output Specification:
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
//input :树中总结点数N 非叶子结点数M // 非叶子结点值ID 此非叶子结点的孩子数k 此非叶子结点的孩子值id[i] (M个非叶子结点) //output: 每层的叶子结点数量 //解题关键:确定每个结点有无孩子结点的标志值tag,每个结点的高度,设置父节点参数nodes[child].parent = ID; //问题:存在非叶子节点的hight在读入当前行时还未知的情况,可以先存入结点的父子关系,然后输入结束再计算hight /*问题例子:9 4 01 2 02 03 04 3 07 08 09 03 2 05 06 02 1 04 */ #include<stdio.h> #include<iostream> using namespace std; typedef struct Node{ int hight;//结点所处高度 int tag;// tag为0,则没有孩子,为1则有孩子 int parent;//父节点 }; Node nodes[100]; //初始化是100个 int main() { /*step1:构建树*/ int N; //树中总结点数 int M; //树中非叶子结点总数 cin >> N; cin >> M; //初始化 for(int i = 1;i <= N;i++) { nodes[i].hight = 1; nodes[i].tag = 0; nodes[i].parent = 0; } //存入父子结点关系 int ID,k,child; for(int i = 0;i < M;i++) { cin >> ID; cin >> k; nodes[ID].tag = 1; for(int j = 0;j < k;j++) { cin >> child; nodes[child].parent = ID; //nodes[child].hight = nodes[ID].hight + 1; } } //存入高度 for(int i = 1;i <=N;i++) { for(int j = i + 1;j <= N;j++) { if(nodes[j].parent == i) { nodes[j].hight = nodes[i].hight + 1; } } } /*step2:统计每层的叶子结点数,并输出*/ //确定树的高度 int maxh = 1; for(int i = 1;i <= N;i++) { if (maxh < nodes[i].hight) { maxh = nodes[i].hight; } } //确定每层高度的叶子节点数 int result[100] = {0};//每层高度的叶子节点数 for(int i = 1;i <= N;i++) { if (nodes[i].tag == 0) { result[nodes[i].hight]++; } } //输出 for(int i = 1;i < maxh;i++) { cout << result[i] << " "; } cout << result[maxh]<<endl; return 0; }