Cod sursa(job #1651888)

Utilizator IoanaPPascu Ioana IoanaP Data 14 martie 2016 09:10:06
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>

using namespace std;

int n, m, i, x, y;
vector <vector <int> > graph;
vector <bool> viz;
stack <int> st, st2;
stack <int> s;
ifstream f ("sortaret.in");
ofstream g ("sortaret.out");

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

    int elem;
    bool found;
    s.push (vertex);
    viz[vertex] = true;
    while (!s.empty()) {
        elem = s.top();
        found = false;
        for (i = 0; i < graph[elem].size() && !found; i++)
           if (!viz[graph[elem][i]]) found = true;
        if (found) {
            i--;
            s.push (graph[elem][i]);
            viz [graph[elem][i]] = true;
        }
         else {
            st.push (s.top()); s.pop();
         }
    }
}


int main()
{
    f >> n >> m;
    graph.resize(n);
    viz.resize(n, false);
    for (i = 0; i < m; i++) {
        f >> x >> y;
        x--; y--;
        graph[x].push_back(y);
    }
    for (i = 0; i < n; i++) {
        if (!viz[i]) DFS(i);
    }
    while (!st.empty()) {
        g << st.top() + 1 << " ";
        st.pop();
    }
    f.close();
    g.close();
    return 0;
}