zoukankan      html  css  js  c++  java
  • 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

    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

    #include "iostream"
    #include "vector"
    using namespace std;
    struct Node {
        int no;
        int child_nums = 0;
        vector<int >childs;
    };
    void dfs(Node tree[],int level[],int depth,int id) {
        if (level[depth] == -1)
            level[depth] = 0;
        if (tree[id].child_nums == 0)
        {
            level[depth]++;
            return;
        }
    
        for (int i = 0; i < tree[id].childs.size(); i++) {
            dfs(tree, level, depth + 1, tree[id].childs[i]);
        }
    }
    int main() {
        int n, m;
        Node tree[100];
        cin >> n >> m;
        while (m--) {
            int id, k;
            cin >> id;
            tree[id].no = id;
            cin >> k;
            tree[id].child_nums = k;
            while (k--) {
                int c;
                cin >> c;
                tree[id].childs.push_back(c);
            }
        }
        int level[100];
        for (int i = 0; i < 100; i++)
            level[i] = -1;
        dfs(tree, level, 1, 1);
        bool first = true;
        for (int i = 0; i < 100; i++)
            if (level[i] != -1) {
                if (first)
                    cout << level[i];
                else
                    cout << " " << level[i];
                first = false;
            }
        cout << endl;
        return 0;
    }
    0 1


  • 相关阅读:
    web site 和 web application的区别
    Windows Phone开发(10):常用控件(上)
    WPF绑定ListBox
    Cookies的实际存储位置
    parse_str() 函数把查询字符串解析到变量中。
    str_repeat() 函数把字符串重复指定的次数。
    搭建Git本地服务器
    windows下github 出现Permission denied (publickey).解决方法
    ReadSolve 规格严格
    Scp命令(转载) 规格严格
  • 原文地址:https://www.cnblogs.com/minesweeper/p/6279745.html
Copyright © 2011-2022 走看看