Cod sursa(job #2485067)

Utilizator iustin948Homoranu Iustin iustin948 Data 31 octombrie 2019 22:25:17
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 50005
#include <stack>
using namespace std;
ifstream fin("sortaret.in");
ofstream fout("sortaret.out");
int n, m;
vector <int> graph[NMAX];
bool visited[NMAX];
stack <int> nodes;
void Read()
{
    int x, y;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        graph[x].push_back(y);
    }
}

void TopSort(int x)
{
    visited[x] = true;
    vector <int> :: iterator it;
    for(it = graph[x].begin(); it < graph[x].end(); it++)
                if(visited[*it] == 0)
                    TopSort(*it);
    nodes.push(x);
}

void Solve()
{
    for(int i = 1; i <= n; i++)
        if(visited[i] == 0)
            TopSort(i);
    while(!nodes.empty())
    {
        fout << nodes.top() << " ";
        nodes.pop();
    }
}

int main()
{
    Read();
    Solve();
    return 0;
}