Cod sursa(job #3214657)

Utilizator _andrei4567Stan Andrei _andrei4567 Data 14 martie 2024 12:00:50
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
///cu set sau cu queue

#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

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

const int N = 5e4;
int pred[N + 1];

vector <int> g[N + 1], topo;

queue <int> q;

int n, m, x, y;

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        cin >> x >> y;
        g[x].push_back(y);
        pred[y]++;
    }
    for (int i = 1; i <= n; ++i)
        if (!pred[i])
            q.push(i);
    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        topo.push_back(node);
        for (auto it : g[node])
        {
            --pred[it];
            if (!pred[it])
                q.push(it);
        }
    }
    for (auto it : topo)
        cout << it << ' ';
    return 0;
}