Cod sursa(job #1651875)

Utilizator y0rgEmacu Geo y0rg Data 14 martie 2016 08:42:43
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream in("sortaret.in");
ofstream out("sortaret.out");
int n, m, s;
vector< vector<int> > graph;
vector<bool> visited;
stack<int> afisare;

void dfs(int vertex);

int main()
{
    in >> n >> m;

    if (n < 1 || n > 50000 || m < 1 || m > 100000)
        return 1;

    graph.resize(n);
    visited.resize(n, false);
    int x, y;

    for (int i = 0; i < m; i++) {
        in >> x >> y;
        x--;
        y--;
        graph[x].push_back(y);
    }
    in.close();


    for (int i = 0; i < n; i++)
        if (!visited[i]) {
            dfs(i);
        }

    while (!afisare.empty()) {
        out << afisare.top() << " ";
        afisare.pop();
    }

    out.close();
    return 0;
}

void dfs(int vertex)
{
    if (vertex < 0 || vertex > n - 1)
        return;

    stack<int> s;
    int element, i;
    bool found;

    s.push(vertex);
    visited[vertex] = true;

    while (!s.empty()) {
        element = s.top();
        found = false;

        for (i = 0; i < graph[element].size() && !found; i++)
            if (!visited[graph[element][i]]) {
                found = true;
                s.push(graph[element][i]);
                visited[graph[element][i]] = true;
            }

        if (!found) {
            afisare.push(s.top() + 1);
            s.pop();
        }
    }
}