Cod sursa(job #2718418)

Utilizator LawrentiuTirisi Claudiu Lawrentiu Data 8 martie 2021 18:43:52
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("sortaret.in");
ofstream o("sortaret.out");

int main()
{

    int n, m, a, b;
    f >> n >> m;
    vector<int> graph[n + 1];
    vector<int> Q, result;
    int deg[n + 1];
    for (int i = 1; i <= n; i++)
        deg[i] = 0;
    for (int i = 0; i < m; i++)
    {
        f >> a >> b;
        graph[a].push_back(b);
        deg[b]++;
    }
    for (int i = 1; i <= n; i++)
    {
        if (deg[i] == 0)
        {
            Q.push_back(i);
        }
    }

    int node, node2;
    vector<int>::iterator i;
    while (!Q.empty())
    {
        node = Q.back();
        Q.pop_back();
        result.push_back(node);
        while (!(graph[node].empty()))
        {
            node2 = graph[node].back();
            deg[node2]--;
            if (deg[node2] == 0)
            {
                Q.push_back(node2);
            }
            graph[node].pop_back();
        }
    }

    for (i = result.begin(); i != result.end(); ++i)
        o << *i << " ";
}