1004. Counting Leaves (30)
来源:互联网 发布:mysql e 执行sql 编辑:程序博客网 时间:2024/05/17 04:04
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 101 1 02Sample Output
0 1
#include<iostream>using namespace std;int cntLeaves[100] = {0};int treeLevel = 0;struct childLink{int id;childLink *next;childLink(){ next = NULL; }};struct Node{int childNum;childLink *childHead;Node(){ childNum = 0; childHead = NULL; }}*node;void countLeaves(int level,int id){childLink *link = node[id].childHead;if (treeLevel < level)treeLevel = level;while (link){if (node[link->id].childNum == 0)++cntLeaves[level];elsecountLeaves(level+1,link->id);link = link->next;}}int main(){int m, n, id;node = new Node[101];cin >> n >> m;for (int i = 0; i < m; ++i){cin >> id;cin >> node[id].childNum;childLink *current = new childLink();for (int j = 0; j < node[id].childNum; ++j){childLink *link = new childLink();cin >> link->id;if (!node[id].childHead){node[id].childHead = link;current = link;}else{current->next = link;current = link;}}}countLeaves(1,01);for (int i = 0; i < treeLevel; ++i)cout << cntLeaves[i] << " ";cout << cntLeaves[treeLevel];return 0;}
测试结果:
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- ssh远程到远程服务器(非22端口号及非root登录)
- (java)异常处理原理和原则
- MVC 原理
- 使用Xcode调试器
- 第一个MapReduce程序笔记
- 1004. Counting Leaves (30)
- leetcode-1 Two Sum
- 访问者模式
- Tomcat内存溢出
- mongoDB的MapReduce简介
- Python编程基础之七条件和循环
- DATABASE SQL
- 中介者模式
- [IOS 开发] GCD中 QUEUE 和 async/sync