Cod sursa(job #3343518)

Utilizator rapidu36Victor Manz rapidu36 Data 27 februarie 2026 17:42:19
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int N = 5e4;

vector <int> ls[N+1];
int nr_pred[N+1];

int main()
{
    ifstream in("sortaret.in");
    ofstream out("sortaret.out");
    int n, m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        ls[x].push_back(y);
        nr_pred[y]++;
    }
    in.close();
    queue <int> q;
    for (int i = 1; i <= n; i++)
    {
        if (nr_pred[i] == 0)
        {
            q.push(i);
        }
    }
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        out << x << " ";
        for (auto y: ls[x])
        {
            nr_pred[y]--;
            if (nr_pred[y] == 0)
            {
                q.push(y);
            }
        }
    }
    out << "\n";
    out.close();
    return 0;
}