Cod sursa(job #2574035)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 5 martie 2020 20:04:51
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");
const int MAXN = 50005;

vector<int> graph[MAXN];
int gr[MAXN], n, m;
queue<int> q;

void read()
{
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        ++gr[y];
    }
}

void solve()
{
    for (int i = 1; i <= n; ++i)
        if (gr[i] == 0)
            q.push(i);
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (const auto& it: graph[node]) {
            --gr[it];
            if (gr[it] == 0)
                q.push(it);
        }
        fout << node << ' ';
    }
}

int main()
{
    read();
    solve();
    return 0;
}