Cod sursa(job #2892251)

Utilizator ChingChengHonChiCiucanu Stefan ChingChengHonChi Data 21 aprilie 2022 14:08:43
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>
#include <type_traits>
#include <vector>
#include <array>
using namespace std;

#define lld long long int
#define sh short

ifstream cin("sortaret.in");
ofstream cout("sortaret.out");

int n, m;
vector<int> g[50001]; //actual graph
array<int, 50001> d, q{}; //degree and the end output
array<bool, 50001> v;

void depthsys (int i) { // depth analasys
    for (auto s : g[i]) {
        --d[s];
        if (!d[s] && !v[s]) {
            q[++q[0]] = s;
            v[s] = 1;
            depthsys(s);
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int a, b;
    cin >> n >> m;
    while (m--) {
        cin >> a >> b;
        g[a].push_back(b);
        ++d[b];
    }

    for (int i = 1; i <= n; ++i) {
        if (v[i] || d[i])
            continue;
        q[++q[0]] = i;
        v[i] = 1;
        depthsys(i);
    }

    for (int i = 1; i <= n; ++i)
        cout << q[i] << ' ';
    return 0;
}