Cod sursa(job #2571874)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 5 martie 2020 10:35:04
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

const int N_MAX = 5e4 + 1;

int N, M;
vector<vector<int>> graph(N_MAX, vector<int>());

vector<int> in_deg(N_MAX, 0);
queue<int> answer;
queue<int> aux;

int main()
{
    fin >> N >> M;

    for(int x, y, i = 1; i <= M; ++i)
    {
        fin >> x >> y;

        graph[x].push_back(y);

        ++in_deg[y];
    }

    for(int i = 1; i <= N; ++i)
    {
        if(in_deg[i] == 0)
        {
            aux.push(i);
        }

    }


    while(aux.empty() == false)
    {
        int node = aux.front();
        aux.pop();

        answer.push(node);

        for(int next : graph[node])
        {
            --in_deg[next];

            if(in_deg[next] == 0)
            {
                aux.push(next);
            }
        }
    }

    while(answer.empty() == false)
    {
        fout << answer.front() << ' ';
        answer.pop();
    }
}