Cod sursa(job #2569350)

Utilizator MichaelXcXCiuciulete Mihai MichaelXcX Data 4 martie 2020 11:54:11
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>

#define in  "sortaret.in"
#define out "sortaret.out"

using namespace std;

const int NMAX = 50005;
int N, M, deg[NMAX], Q[NMAX];
vector<int> G[NMAX];

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    freopen(in, "r", stdin);
    freopen(out, "w", stdout);

    cin >> N >> M;
    for(; M; M--) {
        int x, y;
        cin >> x >> y;
        G[x].push_back(y);
        deg[y]++;
    }

    int x;
    for(x = 1; x <= N; ++x)
        if(!deg[x])
            Q[++Q[0]] = x;

    for(int i = 1; i <= N; ++i) {
        x = Q[i];
        for(auto it : G[x]){
            deg[it]--;
            if(!deg[i])
                Q[++Q[0]] = it;
        }
    }

    for(int i = 1; i <= N; ++i)
        cout << Q[i] << ' ';

    return 0;
}