• PAT 1004 Counting Leaves


    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, the number of nodes in a tree, and M (<), 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
    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    #define MAXN 500
    
    vector<vector<int>> vec;
    
    int to_int(string sx){
        int sum = 0;
        sum += sx[0]-'0';
        sum = sum*10+(sx[1]-'0');
        return sum;
    }
    
    
    
    int main(){
    
        int n,m;
        cin >> n >> m;
        vec.resize(n+1);
        for(int i=0;i < m;i++){
            string s; cin >> s;
            int x = to_int(s);
            int K; cin >> K;
            for(int j=0;j < K;j++){
                string temp; cin >> temp;
                vec[x].push_back(to_int(temp));
            }
        }
    
    
    
        queue<int> que;
        que.push(1);
        while(!que.empty()){
            int len = que.size();
            int cnt = 0;
            for(int i=0;i < len;i++){
                int t = que.front();que.pop();
                if(vec[t].size()){
                    for(int j=0;j < vec[t].size();j++){
                        que.push(vec[t][j]);
                    }
                }
                else cnt++;
            }
            cout << cnt;
            if(!que.empty()) cout << " ";
        }
    
    
        return 0;
    }

    这题也30分??

    树看成一个有向图,用邻接表储存,然后bfs遍历即可

     
  • 相关阅读:
    简单svg动画
    如何开发jQuery插件
    Nodejs的模块系统以及require的机制
    Nodejs的http模块
    DOM详解
    利用powershell进行远程服务器管理(命令行模式)
    关于storm群集容错概念的简单介绍
    powershell利用winform批量执行tsql语句
    nginx往后端转发时需要注意的两个问题
    解决hyerv的linux虚拟机网卡地址重启发生变化的问题
  • 原文地址:https://www.cnblogs.com/cunyusup/p/10811165.html
Copyright © 2020-2023  润新知