Cod sursa(job #1664983)

Utilizator Bijoux12Andreea Gae Bijoux12 Data 26 martie 2016 15:17:58
Problema Sortare topologica Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>

using namespace std;

unsigned int n, m;
vector<vector<int> > graph;
vector<bool> visited;
queue<int> solutie;

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

void dfs(unsigned int vertex)
{
    if (vertex<0 || vertex>n - 1)
        return;
    stack<int> s;
    unsigned int element, i;
    bool found;
    s.push(vertex);
    visited[vertex] = true;
    solutie.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]);
            solutie.push(graph[element][i]);
            visited[graph[element][i]] = true;
        }
        else
            s.pop();
    }
}

int main()
{
    f >> n >> m;
    graph.resize(n);
    visited.resize(n, false);
    unsigned int x, y, i;
    for (i = 0; i<m; i++)
    {
        f >> 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);
    cout << endl;
    for (i = 0; i < n; i++)
    {
        g << solutie.front()+1 << " ";
        solutie.pop();
    }
    f.close();
    g.close();
    return 0;
}