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 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
.
The input ends with N 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
解题思路:
- 树的表示:由于题目中树不是二叉树,因此需要其他形式来表示树。这里采用map和vector容器实现树的表示,map关键字为根结点ID,第二项为vector容器,存储子结点的ID。
-
统计每层叶结点数量:将根的ID压入一个层次向量中,last表示当前层次最后(最右边)一个结点,将last初值设为树的根;接下来读取层次向量中第一个元素,将它所有子结点压入层次中向量,如果没有子结点,计数器cnt加1。如果第一个元素等于last,则说明这一层结点统计完毕,cnt压入输出向量中,然后清零,将last重新赋值为层次向量中最后一个元素,即指向下一层次最后一个元素。当初向量第一个元素,此时向量非空,则继续循环。
AC代码:
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main(){
int N,M,K,i;
map<string,vector<string> >tree;
vector<string> q;
vector<int> ans;
cin>>N>>M;
for(i=0;i<M;i++){
string a,b;
cin>>a>>K;
while(K--){
cin>>b;
tree[a].push_back(b);
}
}
q.push_back("01");
string last="01",now;
int cnt=0,j;
for(i=0;i<q.size();i++){
for(j=0;j<tree[q[i]].size();j++){
now=tree[q[i]][j];
q.push_back(now);
}
if(!j)
cnt++;
if(q[i]==last){
last=now;
ans.push_back(cnt);
cnt=0;
}
}
for(i=0;i<ans.size()-1;i++)
printf("%d ",ans[i]);
printf("%d",ans[i]);
return 0;
}