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


  • 相关阅读:
    [知识点]计算几何I——基础知识与多边形面积
    [旧版][知识点]SPFA算法
    [旧版][知识点]A*搜索(启发式搜索)
    [知识点]线段树
    [小工具]ChemistryHelper
    [考试]20150314
    [知识点]Cantor展开
    [旧版][知识点]拓扑排序
    [无效]网络流之Dinic算法
    [SCOI2005]扫雷Mine
  • 原文地址:https://www.cnblogs.com/minesweeper/p/6279745.html
Copyright © 2011-2022 走看看