• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
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遍历即可

 
posted on 2019-05-05 09:22  村雨sup  阅读(138)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3