Cod sursa(job #2725377)

Utilizator andreitudorpAndrei Tudor Popescu andreitudorp Data 18 martie 2021 20:58:50
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <vector>

using namespace std;

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

#define MAXN 50005

int deg[MAXN], q[MAXN];
vector<int> graph[MAXN];

int main()
{
    int n, m;
    cin >> n >> m;

    int x, y;

    for(int i = 0 ; i <= m; i++)
    {
        cin >> x >> y;

        graph[x].push_back(y);
        deg[y]++;
    }

    for(x = 1; x <= n; x++)
        if(deg[x] == 0)
            q[++q[0]] = x;

    vector<int>::iterator it;

    for(int i = 1; i <= n; i++)
    {
        x = q[i];

        for(it = graph[x].begin(); it != graph[x].end(); it++)
        {
            deg[*it]--;

            if(deg[*it] == 0)
                q[++q[0]] = *it;
        }
    }

    for(int i = 1; i <= n; i++)
        cout << q[i] << " ";

    return 0;
}