1004 Counting Leaves (30 分)
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 , the number of nodes in a tree, and (), the number of non-leaf nodes. Then 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 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
题目解读:输入一串树的节点,及这些节点的孩子的编号,01为跟节点,输出每一层的叶节点个数。
解题思路:用vector<int> T[100],就是一个二维数组储存叶节点和孩子的编号,有点像存图的边。这道题方便的就是01一定是根节点,这样就可以DFS得到每个节点的高度,把没有孩子的节点按层记数,因为中间可能有很多0,所以记录一下最深层。这次卡在了递归里的++deep,deep++每一次都会给deep+1,但其实我要的就是deep+1,慎用++的操作。
AC代码
#include <iostream>
#include <vector>
using namespace std;
int leave[100];
vector<int> T[100];
int n,m;
int maxdep = 0;
void DFS(int root,int deep){
if(T[root].size() == 0 )leave[deep]++;
if(maxdep<deep)
maxdep = deep;
for( int i = 0 ; i < T[root].size() ; i ++ ){
DFS(T[root][i],deep+1);
}
}
int main(int argc, const char * argv[]) {
cin >> n >> m;
int ID,k,c;
for( int i = 0 ; i < m ; i ++ ){
cin >> ID >> k;
for( int j = 0 ; j < k; j ++ ){
cin >> c;
T[ID].push_back(c);
}
}
DFS(1,0);
for( int i = 0 ; i < maxdep ; i ++ ){
cout << leave[i] << " ";
}
cout << leave[maxdep];
//std::cout << "Hello, World!\n";
return 0;
}
0 条评论