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 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题意:数每层的叶子结点 用dfs的前序遍历或者bfs的层序遍历均可,但是dfs明显简单一点 用一个数组来存每层的叶子结点个数 dfs就是递归,注意递归式和递归边界即可 怎么存树的,看柳神的学到了用vector v[100]来存,将i的每个子结点push_back在v[i]下 递归式就是dfs(v[index][i], depth+1);因为这里遍历的是当前结点的子结点,所以要当前结点+1 递归边界就是v[index].size() == 0,证明这是个叶子结点,将数组中当前深度的叶子节点数++,并更新一下maxdepth,然后return
#include<iostream> #include<cstdio> #include<vector> using namespace std; vector<int> v[100];//存放每个结点的子结点,v[1]={2,3},证明1的结点有2和3 int book[100] ={0}, maxdepth = -1; void dfs(int index, int depth){ if(v[index].size() == 0){ book[depth]++; maxdepth = max(depth,maxdepth); return; } for(int i = 0; i < v[index].size(); i++){ dfs(v[index][i], depth + 1); } } int main(){ int n, m, k; int root, child; cin >> n >> m; for(int i = 0; i < m; i++){ cin >> root >> k; for(int j = 0; j < k; j++){ cin >> child; v[root].push_back(child); } } dfs(1,0); cout << book[0]; for(int i = 1; i <= maxdepth; i++){ printf(" %d",book[i]); } return 0; }