Cod sursa(job #1651882)

Utilizator IoanaPPascu Ioana IoanaP Data 14 martie 2016 08:58:56
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 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;
ifstream f ("sortaret.in");
ofstream g ("sortaret.out");

void DFS (int vertex){
    int i;
    if (vertex < 0 || vertex > n-1) return;
    stack <int> s;
    int elem;
    bool found;
    s.push (vertex);
    st.push (vertex);
    viz[vertex] = true;
    //cout << "DFS: " << vertex << " ";
    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]);
            st.push (graph[elem][i]);
            //cout << graph[elem][i] << " ";
            viz [graph[elem][i]] = true;
        }
         else {
            s.pop();
            //cout << st.top() + 1 << " ";
            st2.push (st.top() + 1); st.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 (!st2.empty()) {
        g << st2.top() << " ";
        st2.pop();
    }
    f.close();
    g.close();
    return 0;
}