您的位置:首页 > 其它

1004. Counting Leaves (30)

2014-11-02 22:05 337 查看
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 1
01 1 02

Sample Output

0 1

#include <iostream>
#include <vector>
#include <map>
using namespace std;

const int MAX_SIZE=100;
typedef struct node
{
int id;
int childs_num;
vector<int> childs;
}Node;

void count_leafs(const Node *tree,Node node,map<int,int>& m,int depth)
{
if(m[depth]==0) m[depth]=0;
if(node.childs_num==0){
++m[depth];
return;
}
vector<int> childs=node.childs;
for(size_t i=0;i<childs.size();++i){
count_leafs(tree,tree[childs[i]],m,depth+1);
}
}

int main()
{
int n, m;
cin>>n>>m;
Node tree[MAX_SIZE];
for(int i=0;i<MAX_SIZE;++i){
tree[i].id=0;
tree[i].childs_num=0;
}
int id,k;
while(m--){
cin>>id>>k;
tree[id].id=id;
tree[id].childs_num=k;
int child;
while(k--){
cin>>child;
tree[id].childs.push_back(child);
}
}
map<int,int> result;
count_leafs(tree,tree[1],result,1);
bool first=true;
for(map<int,int>::iterator iter=result.begin();iter!=result.end();++iter){
if(first){
cout<<iter->second;
first=false;
}else{
cout<<" "<<iter->second;
}
}
return 0;
}
/*
9 5
01 2 02 03
02 1 04
03 2 05 06
05 2 07 08
08 1 09
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: