zoukankan      html  css  js  c++  java
  • PAT(Advanced Level)A1094. The Largest Generation

    题意

    树的层序遍历的问题,找到结点数最多的一层,输出结点树和对应层号

    思路

    • 看到是树层序遍历就立马反应过来用BFS做,可以说是裸模版的题目了
    • 层序遍历在每次扩展状态的时候都是取一层的结点数进行扩展,此时就可以直接比较来找题目要求的解了

    代码

    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <vector>
    #include <queue>
    #include <math.h>
    using namespace std;
    vector<int> tree[110];
    void bfs(int st, int& numbers, int& level)
    {
        queue<int> q;
        q.push(st);
        int depth = 1;
        while(!q.empty())
        {
            int size = q.size();
            if(size > numbers)     //和解进行比较,找最好
            {
                numbers = size;
                level = depth;
            }
            for(int i=0;i<size;i++)
            {
                auto cur = q.front();
                q.pop();
                for(int j=0;j<tree[cur].size();j++)
                    q.push(tree[cur][j]);
            }
            depth++;
        }
    }
    int main()
    {
        int n, m;
        cin >> n >> m;
        int id, k, t;
        for(int i=0;i<m;i++)
        {
            cin >> id >> k;
            for(int j=0;j<k;j++)
            {
                cin >> t;
                tree[id].emplace_back(t);
            }
        }
        int level_numbers = -1, level = -1;
        bfs(1, level_numbers, level);
        cout << level_numbers << " " << level;
        return 0;
    }
    
  • 相关阅读:
    centos redis 安装 php-redis扩展安装 及使用
    mysql 大数据分页查询优化
    nginx https ssl 配置
    mysql 集群 数据同步
    linux 挂载U盘
    centos yum 没有可用软件包 nginx。
    nginx 负载均衡 反向代理
    nginx 配置
    mac 多php版本安装
    Foundation框架
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/13769712.html
Copyright © 2011-2022 走看看