求字典序最小的拓扑排序

洛谷
相比求任意一个拓扑序的代码,把队列改成小根堆即可。

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
//#define int ll
const int N = 1e5 + 10;
int id;
int head[N];
int to[N];
int nx[N];
void add(int x,int y) {
    to[id] = y;
    nx[id] = head[x];
    head[x] = id++;
}
int in[N];
signed main() {
    cin.tie(nullptr)->ios::sync_with_stdio(false);
    int n, m;
    cin >> n >> m;
    set<pair<int,int>> st0;
    for (int i = 1; i <= m; i++) {
        int x,y;
        cin >> x >> y;
        st0.insert({x,y});
    }
    id = 1;
    for (auto i : st0) {
        add(i.first,i.second);
        in[i.second]++;
    }
    priority_queue<int,vector<int>, greater<int> > q;
    for (int i = 1; i <= n; i++) {
        if (in[i] == 0) {
            q.push(i);
        }
    }
    while(q.size()) {
        int t = q.top();
        cout << t << " ";
        q.pop();
        for (int i = head[t]; i > 0; i = nx[i]) {
            int cur = to[i];
            if (in[cur] == 0) continue;
            in[cur]--;
            if (in[cur] == 0) q.push(cur); 
        }
    }
    return 0;
}   /* created: 2024-12-08 17:04 author: Egrvigrf */
github