Cod sursa(job #1710929)

Utilizator georgel69Mihai George georgel69 Data 30 mai 2016 04:43:37
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 fin("sortaret.in");
ofstream fout("sortaret.out");
int n, m, s;
vector< vector<int> > graph;
vector<bool> visited;
stack<int> sortat;

void dfs(int vertex);

int main()
{
    fin >> 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++) {
        fin >> x >> y;
        x--;
        y--;
        graph[x].push_back(y);
    }
    fin.close();


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

    while (!sortat.empty()) {
        fout << sortat.top() << " ";
        sortat.pop();
    }

    fout.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) {
            sortat.push(s.top() + 1);
            s.pop();
        }
    }
}