Cod sursa(job #3350650)

Utilizator Alex_at_gameIustin-Alexandru Frateanu Alex_at_game Data 11 aprilie 2026 15:54:49
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define all(v) begin(v), end(v)
#define al(v, l, r) begin(v) + l, begin(v) + r + 1
#define sz(v) (int)v.size()
#define pb push_back
#define pob pop_back
#define fs first
#define sd second

constexpr int inf = 2e9;
constexpr ll infll = 4e18;
constexpr int N = 50005;

int n, m, in[N];
vector<int> g[N];
signed main() {
    ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
    freopen("sortaret.in", "r", stdin);
    freopen("sortaret.out", "w", stdout);

    cin >> n >> m;
    for (int i = 0, x, y; i < m; ++i) {
        cin >> x >> y;
        g[x].pb(y);
        in[y]++;
    }

    int mn = inf;
    for (int i = 1; i <= n; ++i) {
        if (mn > in[i]) {
            mn = in[i];
        }
    }

    queue<int> q;
    vector<int> topo;

    for (int i = 1; i <= n; ++i) {
        if (in[i] == mn) {
            q.push(i);
            in[i] = -1;
        }
    }

    while (!q.empty()) {
        int x = q.front();
        q.pop();
        topo.pb(x);

        for (int y : g[x]) {
            in[y]--;

            if (in[y] == 0) {
                q.push(y);
            }
        }
    }

    for (int x : topo) {
        cout << x << " ";
    }
}