Cod sursa(job #3032667)

Utilizator rapidu36Victor Manz rapidu36 Data 22 martie 2023 16:14:21
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <queue>

using namespace std;

const int N = 5e4;
const int M = 1e5;

struct element
{
    int vf, urm;
};

element v[M+1];
int lst[N+1], nrp[N+1], nr;

void adauga(int x, int y)
{
    v[++nr].vf = y;
    v[nr].urm = lst[x];
    lst[x] = nr;
    nrp[y]++;
}

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;
        adauga(x, 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();
        out << x << " ";
        for (int p = lst[x]; p != 0; p = v[p].urm)
        {
            int y = v[p].vf;
            nrp[y]--;
            if (nrp[y] == 0)
            {
                q.push(y);
            }
        }
    }
    in.close();
    out.close();
    return 0;
}