1004. Counting Leaves (30)

来源:互联网 发布:傲剑金蛇数据 编辑:程序博客网 时间:2024/06/13 07:58

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
题目大意:给出总共的节点n和非叶节点m,再给出m行根结点id和每个根的k个儿子,以及k个儿子的id,01默认为根
思路:用vector二维数组记录,然后dfs,如果当前根没有儿子,则该层就++;

#include <iostream>#include <vector>#include <algorithm>using namespace std;const int maxn = 105;int n, m, maxLevel;vector<int> node[maxn];int level[maxn];void dfs(int root, int l){    if(node[root].empty()){        maxLevel = max(maxLevel, l);        level[l]++;        return ;    }     for(int i = 0; i < node[root].size(); ++i){        dfs(node[root][i], l + 1);    }}int main(){    int id, k, child;    scanf("%d %d", &n, &m);     for(int i = 0; i < m; ++i){        scanf("%d %d", &id, &k);        for(int j = 0; j < k; ++j){            scanf("%d", &child);            node[id].push_back(child);        }    }       dfs(1, 0);    for(int i = 0; i <= maxLevel; ++i){        if(i)            printf(" ");        printf("%d", level[i]);     }    return 0;}
0 0