A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.node
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:ios
ID K ID[1] ID[2] ... ID[K]git
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.算法
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.數組
2 1
01 1 02app
0 1spa
算法要求求出每一層沒有孩子節點的個數並依次輸出,本文采用vector存儲結點,固然你能夠本身定義結構體。而後用遞歸計算每一層的沒有孩子結點的個數,這時就必須有個數組book[depth]來記錄啦,下標表明層數,對應的值表示這一層無孩子結點個數。遞歸中止的條件爲 :vector[index].size()==0 說明當前結點沒有孩子結點,使book[depth]++,下面貼出代碼。
3d
// 1004 Counting Leaves.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <vector> using namespace std; vector<int> vec[100]; int maxDepth=-1; int book[100]={0}; /** 4 2 01 2 02 03 02 1 04 **/ void dfs(int index,int depth){ if(vec[index].size()==0){ book[depth]++; if(depth>maxDepth) maxDepth=depth; return; } for(int i=0;i<vec[index].size();i++) dfs(vec[index].at(i),depth+1); } int main(int argc, char* argv[]) { int N,M,node,k,leaf; cin >>N>>M; for(int i=0;i<M;i++){ cin >>node>>k; for(int j=0;j<k;j++){ cin >> leaf; vec[node].push_back(leaf); } } dfs(1,0); cout<<book[0]; for(int j=1;j<=maxDepth;j++){ cout<<" "<<book[j]; } return 0; }