Cod sursa(job #2979581)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 15 februarie 2023 16:38:09
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
/// [A][M][C][B][N] ///
#include <bits/stdc++.h>
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const char sp = ' ', nl = '\n';
using namespace std;
ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

const int nmax = 5e4;
int d[nmax + 1]{ 0 };
vector<int> g[nmax + 1];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, m;
    fin >> n >> m;
    while (m--) {
        int u, v;
        fin >> u >> v;
        g[u].push_back(v);
    }
    for (int i = 1; i <= n; ++i) {
        sort(g[i].begin(), g[i].end());
        g[i].resize(unique(g[i].begin(), g[i].end()) - g[i].begin());
        for (auto& j : g[i]) {
            d[j]++;
        }
    }
    queue<int> q;
    for (int i = 1; i <= n; ++i) {
        if (d[i] == 0) {
            q.push(i);
        }
    }
    while (q.size()) {
        int u = q.front();
        fout << u << sp;
        q.pop();
        for (auto& v : g[u]) {
            if (--d[v] == 0) {
                q.push(v);
            }
        }
    }
}