Cod sursa(job #2877377)

Utilizator MihneaCadar101Cadar Mihnea MihneaCadar101 Data 24 martie 2022 18:02:28
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

const int nmax = 5e4 + 5;

int n, m, cnt[nmax];
vector <int> v[nmax], ans;
queue <int> q;

void sortare_top() {
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        ans.push_back(x);
        for (auto it = v[x].begin(); it != v[x].end(); ++it) {
            --cnt[*it];
            if (!cnt[*it])
                q.push(*it);
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
        ++cnt[y];
    }

    for (int i = 1; i <= n; ++i) {
        if (!cnt[i])
            q.push(i);
    }

    sortare_top();
    for (int i : ans)
        fout << i << ' ';
    return 0;
}