PAT甲级真题及训练集(24)--1004. Counting Leaves (30)

来源:互联网 发布:java程序员的简历 编辑:程序博客网 时间:2024/06/05 00:57

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

提交代码


/**作者:一叶扁舟时间:21:36 2017/7/8思路:统计树每一层结点的个数*/#include <stdio.h>#include <stdlib.h>#include <algorithm>#include <stack>#include <queue>#include <math.h>#include <string.h>#include <vector>using namespace std;#define SIZE 100001typedef struct TreeNode{int data;vector<int> child;}TreeNode;int level[SIZE] = { 0 };//定义每一层统计树节点数//定义的树,可以用结构体,也可以用直接用vector<int> tree来定义TreeNode treeNode[SIZE];int IsRoot[SIZE] = { 0 };//0默认是根节点,1是子结点//树的最大深度int maxLevel = 0;//得到每一层结点个数void getLevelNodeNum(int rootNum, int depth){//到了叶子节点if (treeNode[rootNum].child.size() == 0){level[depth]++;if (depth > maxLevel){maxLevel = depth;}return;}for (unsigned int i = 0; i < treeNode[rootNum].child.size(); i++){//递归访问root的子结点getLevelNodeNum(treeNode[rootNum].child[i], depth + 1);}}int getTreeRoot(int N){for (int i = 1; i <= N; i++){if (IsRoot[i] != 1){return i;}}return 0;}int main(){int N;int  m;//有孩子结点的个数scanf("%d %d", &N, &m);for (int i = 0; i < m; i++){int num, nodeNo;//nodeNo父节点,num为父节点nodeNo后面的子结点的个数scanf("%d %d", &nodeNo, &num);for (int j = 0; j < num; j++){int temp;scanf("%d", &temp);IsRoot[temp] = 1;//子结点再这里出现了,说明不可能是根节点//存入对应的孩子结点treeNode[nodeNo].child.push_back(temp);}}//得到根结点int rootNum = getTreeRoot(N);getLevelNodeNum(rootNum, 1);double result = 0;//输出每一层的结点个数for (int i = 1; i <= maxLevel; i++){//找到depth大于0的printf("%d",level[i]);if (i != maxLevel){printf(" ");}}system("pause");return 0;}