HDU 4857 逃生【拓扑排序反向建图】

题目连接

题目描述

在这里插入图片描述


题解:

为什么要反向建图:
在这里插入图片描述
上面这个例子说明,前面小的不一定排在前面,前面某个点的优先级由它后面最小的那个点决定,但如果它后面的点大,则它一定排在后面,这样就建一个反图,优先队列中大的在顶上,最后将结果反过来就是答案。


AC代码

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <deque>
#include <list>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
//#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
//cout << fixed << setprecision(2);
//cout << setw(2);
const int N = 1e5 + 5, M = 1e9 + 7;

int n, m, ans[N], cnt;
int head[N], Next[N], ver[N], tot;
int in[N];

void add(int u, int v) {
    ver[++tot] = v;
    Next[tot] = head[u];
    head[u] = tot;
}

void bfs() {
    priority_queue<int> q;
    for (int i = 1; i <= n; i++) {
        if (in[i] == 0)
            q.push(i);
    }
    while (!q.empty()) {
        int x = q.top();
        q.pop();
        ans[cnt++] = x;
        for (int i = head[x]; i; i = Next[i]) {
            in[ver[i]]--;
            if (in[ver[i]] == 0) q.push(ver[i]);
        }
    }
}

int main() {
    //freopen("/Users/xumingfei/Desktop/ACM/test.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int T;
    cin >> T;
    while (T--) {
        cin >> n >> m;
        cnt = 0, tot = 1;
        int u, v;
        memset(head, 0, sizeof(head));
        for (int i = 0; i < m; i++) {
            cin >> u >> v;
            add(v, u);
            in[u]++;
        }
        bfs();
        for (int i = cnt - 1; i >= 0; i--) {
            cout << ans[i];
            if (i != 0) {
                cout << ' ';
            } else {
                cout << '\n';
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值