1004 Counting Leaves (30 point(s))
1004 Counting Leaves (30 point(s))
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
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.
題目大意:
給定對應的樹的結構.然後給出每一層的葉子節點的數量.
解決:
1.首先是輸入的轉化,要將01 ...02 等等數字轉化成正常的數字,解決方案就是使用sstream 通過string轉化為int
2.其次是樹的儲存和構造,這裡用了vector陣列進行儲存,因為知道範圍,所以直接建立是很方便的
3.最後是樹的層序遍歷,使用queue進行層序遍歷每一層遍歷完之後,直接列印對應的葉子節點的數量
4.注意最後的列印格式
#include<iostream>
#include<vector>
#include<sstream>
#include<string>
#include<queue>
using namespace std;
int strToint(const string &str){
istringstream i(str);
int out;
if(i>>out){
return out;
}
return 0;
}
int main(){
int const MAX = 110;
bool vis[MAX]{false};
int father[MAX];
vector<int>tree[MAX];
queue<int>finder;
fill(father,father+MAX,1);
fill(vis,vis+MAX,0);
int N=0;
int M=0;
cin>>N>>M;
if(N==0){
return 0;
}
for(int i=0;i<M;i++){
string temp;
int num;
cin>>temp>>num;
int id = strToint(temp);
vis[id] =true;
for(int j=0;j<num;j++){
string temp_num;
cin>>temp_num;
int temp_id = strToint(temp_num);
vis[temp_id] = true;
tree[id].push_back(temp_id);
father[temp_id] = id;
}
}
finder.push(1);
int Level =1;
int oldlevel =1;
int Count=0;
bool first=true;
while(!finder.empty()){
int id = finder.front();
finder.pop();
int lenth = tree[id].size();
if(lenth==0){
Count++;
}
for(int i=0;i<lenth;i++){
finder.push(tree[id][i]);
Level = tree[id][i];
}
if(id==oldlevel){
oldlevel = Level;
if(first){
cout<<Count;
first = false;
}else{
cout<<" "<<Count;
}
Count=0;
}
}
return 0;
}
一開始理解錯了,以為是要找到葉子節點並且最後列印從root到該葉子節點的路徑...審題很總要
生僻單詞:
hierarchy
n. 層級;等級制度
pedigree
- n. 血統;家譜
- adj. 純種的
specification
n. 規格;說明書;詳述
sake
- n. 目的;利益;理由;日本米酒
- n. (Sake)人名;(羅)薩克;(日)酒(姓)
seniority
n. 長輩;老資格;前任者的特權