Cod sursa(job #1636394)

Utilizator pavelclaudiu96Pavel Claudiu Stefan pavelclaudiu96 Data 7 martie 2016 09:30:45
Problema Sortare topologica Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>

using namespace std;

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

vector<vector <int> > graph;
vector <bool> visited;
queue <int> sorted;

int n,m;

void dfs(int vertex)
{
    if(vertex < 0 || vertex > n-1)
        return;
    stack<int> s;
    int element;
    bool found;
    int i;
    s.push(vertex);
    visited[vertex]=true;
    sorted.push(vertex);
    while(!s.empty())
    {
        element=s.top();
        found=false;
        for(i=0; i<graph[element].size() && !found; i++)
        {
            if(!visited[graph[element][i]])
                found=true;
        }
        if(found)
        {
            i--;
            s.push(graph[element][i]);
            visited[graph[element][i]]=true;
            sorted.push(graph[element][i]);
        }
        else
        {
            s.pop();
        }
    }

}
int main()
{
    int i,x,y,c=0;
    in>>n>>m;
    graph.resize(n);
    visited.resize(n,false);
    for(i = 0; i < m; i++)
    {
        in>>x>>y;
        x--;
        y--;
        graph[x].push_back(y);
        graph[y].push_back(x);

    }
    for(i = 0; i < visited.size() && i < n; i++)
    {
        if(!visited[i])
        {
            dfs(i);
        }
    }
    for( i = 0; i < n; i++) {
    	out << sorted.front() + 1 << " ";
    	sorted.pop();
    }
    return 0;
}