Cod sursa(job #3293700)

Utilizator _andrei4567Stan Andrei _andrei4567 Data 12 aprilie 2025 12:46:33
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#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];

bool viz[N + 1];

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

int n, m, x, y;

queue <int> q;

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 x = q.front();
        q.pop();
        sol.push_back(x);
        for (auto it : g[x])
        {
            --pred[it];
            if (!pred[it])
                q.push(it);
        }
    }
    for (auto it : sol)
        cout << it << ' ';
    return 0;
}