前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HDU 4857 - 逃生

HDU 4857 - 逃生

作者头像
Reck Zhang
发布2021-08-11 11:52:17
2750
发布2021-08-11 11:52:17
举报
文章被收录于专栏:Reck Zhang

逃生

Problem Description

糟糕的事情发生啦,现在大家都忙着逃命。但是逃命的通道很窄,大家只能排成一行。

现在有n个人,从1标号到n。同时有一些奇怪的约束条件,每个都形如:a必须在b之前。 同时,社会是不平等的,这些人有的穷有的富。1号最富,2号第二富,以此类推。有钱人就贿赂负责人,所以他们有一些好处。

负责人现在可以安排大家排队的顺序,由于收了好处,所以他要让1号尽量靠前,如果此时还有多种情况,就再让2号尽量靠前,如果还有多种情况,就让3号尽量靠前,以此类推。

那么你就要安排大家的顺序。我们保证一定有解。

Input

第一行一个整数T(1 <= T <= 5),表示测试数据的个数。 然后对于每个测试数据,第一行有两个整数n(1 <= n <= 30000)和m(1 <= m <= 100000),分别表示人数和约束的个数。

然后m行,每行两个整数a和b,表示有一个约束a号必须在b号之前。a和b必然不同。

Output

对每个测试数据,输出一行排队的顺序,用空格隔开。

Sample Input

代码语言:javascript
复制
1
5 10
3 5
1 4
2 5
1 2
3 4
1 4
2 3
1 5
3 5
1 2

Sample Output

代码语言:javascript
复制
1 2 3 4 5

Solution

代码语言:javascript
复制
#include <bits/stdc++.h>

int main() {

    std::ios::sync_with_stdio(false);

    std::vector<std::vector<int>> edge = std::vector<std::vector<int>>(30001, std::vector<int>(0));
    std::vector<int> in_degree = std::vector<int>(30001, 0);

    int T;
    std::cin >> T;
    while(T--) {
        int n, m;
        std::cin >> n >> m;
        for(int i = 1; i <= n; i++) {
            edge[i].clear();
            in_degree[i] = 0;
        }

        while(m--) {
            int a, b;
            std::cin >> a >> b;
            in_degree[a]++;
            edge[b].push_back(a);
        }

        std::priority_queue<int, std::vector<int>, std::less<int>> priorityQueue;
        for(int i = 1; i <= n; i++) {
            if(!in_degree[i]) {
                priorityQueue.push(i);
            }
        }

        std::vector<int> res;
        while(!priorityQueue.empty()) {
            int currentIndex = priorityQueue.top();
            priorityQueue.pop();
            res.push_back(currentIndex);
            for(auto nextIndex : edge[currentIndex]) {
                in_degree[nextIndex]--;
                if(!in_degree[nextIndex]) {
                    priorityQueue.push(nextIndex);
                }
            }
        }

        for(int i = static_cast<int>(res.size() - 1); i >= 0; i--) {
            std::cout << res[i] << (i ? " " : "");
        }
        std::cout << std::endl;
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-02-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 逃生
    • Problem Description
      • Input
        • Output
          • Sample Input
            • Sample Output
              • Solution
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档