1004. Counting Leaves (30)
2016-03-29 18:42
260 查看
1004. Counting Leaves (30)
QuestionA 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
My Solution
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <map> #include <vector> using namespace std; map<int, vector<int>>familyTree; int result[101] = {0}; int realLevel = 0; void depthFirstSearch(int id, int level) { //找到leaf-node if (familyTree[id].empty()) { ++result[level]; if (level > realLevel) { realLevel = level; } return; } //没有找到,继续向下找 vector<int>::iterator ite = familyTree[id].begin(); for (; ite != familyTree[id].end(); ++ite) { depthFirstSearch(*ite, level + 1); } } int main(int argc, const char * argv[]) { int N, M; scanf("%d %d", &N, &M); //初始化整张family tree int id, childAmount, childID; for (int i = 0; i < M; ++i) { scanf("%d %d",&id, &childAmount); for (int j = 0; j < childAmount; ++j) { scanf("%d",&childID); familyTree[id].push_back(childID); } } depthFirstSearch(01, 0); for (int i = 0; i <= realLevel; ++i) { if (i == 0) { printf("%d", result[i]); }else { printf(" %d", result[i]); } } printf("\n"); return 0; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析