Cod sursa(job #3040342)

Utilizator AndreiN96Andrei Nicula AndreiN96 Data 29 martie 2023 19:29:08
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int N = 50000;
vector <int> succ[N + 1];
int nrp[N + 1];
vector <int> rez;

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;
        succ[x].push_back(y);
        nrp[y] ++;
    }

    queue <int> q;
    for (int i = 1; i <= n; i ++)
    {
        if (nrp[i] == 0)
        {
            q.push(i);
        }
    }
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        rez.push_back(x);
        for (auto y: succ[x])
        {
            nrp[y] --;
            if (nrp[y] == 0)
            {
                q.push(y);
            }
        }
    }

    for (auto r: rez)
    {
        out << r << ' ';
    }

    in.close();
    out.close();

    return 0;
}