bzoj 4010 [HNOI2015]菜肴制作 贪心+堆+拓扑排序

本文介绍了一种求解字典序最大拓扑排序的方法,通过将有向图的边反向,寻找字典序最大的拓扑排序,并给出了解题思路及C++实现代码。

题面

题目传送门

解法

直接做似乎不太好做

考虑倒着做,将边反向,然后求出字典序最大的拓扑序,最后将这个拓扑序翻转即为答案

为什么这个是正确的??

感觉理性分析一下就可以了吧

时间复杂度:\(O(n\ log\ n)\)

代码

#include <bits/stdc++.h>
#define N 100010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
    x = 0; int f = 1; char c = getchar();
    while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
    while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Edge {
    int next, num;
} e[N * 3];
int n, m, cnt, s[N], ans[N];
void add(int x, int y) {
    e[++cnt] = (Edge) {e[x].next, y};
    e[x].next = cnt;
}
int topsort() {
    int len = 0;
    priority_queue <int> h;
    for (int i = 1; i <= n; i++)
        if (!s[i]) h.push(i);
    while (!h.empty()) {
        int x = h.top(); h.pop(); ans[++len] = x;
        for (int p = e[x].next; p; p = e[p].next) {
            int k = e[p].num; s[k]--;
            if (!s[k]) h.push(k);
        }
    }
    return len == n;
}
int main() {
    int T; read(T);
    while (T--) {
        read(n), read(m); cnt = n;
        for (int i = 1; i <= n; i++)
            e[i].next = 0, s[i] = 0;
        for (int i = 1; i <= m; i++) {
            int x, y; read(x), read(y);
            add(y, x), s[x]++;
        }
        if (topsort()) {
            for (int i = 1; i <= n; i++)
                cout << ans[n - i + 1] << ' ';
            cout << "\n";
        } else cout << "Impossible!\n";
    }
    return 0;
}

转载于:https://www.cnblogs.com/copperoxide/p/9476506.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值