Cod sursa(job #2178283)

Utilizator silvereaLKovacs Istvan silvereaL Data 19 martie 2018 12:20:46
Problema Sortare topologica Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

const int M = 50001;

ifstream fcin("sortaret.in");
ofstream fcout("sortaret.out");

vector<int> V[M];
stack<int> s;
int n, m, x, y;
bool visited[M];

void topologicalSortUt(int snode)
{
    visited[snode] = true;

    for (int i = 0; i < V[snode].size(); ++i)
        if (!visited[V[snode][i]])
            topologicalSortUt(V[snode][i]);

    s.push(snode);
}

void topologicalSort(int snode)
{
    for (int i = snode; i <= n; ++i)
        if (!visited[i])
            topologicalSortUt(i);

    while (!s.empty())
    {
        cout << s.top() << ' ';
        s.pop();
    }
}

int main()
{
    fcin >> n >> m;
    for (int i = 0; i < m; ++i)
    {
        fcin >> x >> y;
        V[x].push_back(y);
    }

    topologicalSort(1);
}