Cod sursa(job #2779389)

Utilizator guzgandemunteIonescu Laura guzgandemunte Data 3 octombrie 2021 16:12:25
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define VMAX 50000
#define WHITE 0
#define GRAY 1
#define BLACK 2
using namespace std;

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

int V, E, x, y;
vector <int> adj[VMAX];
int f[VMAX];
char color[VMAX];
stack <int> topological_sort;

void DFS_visit(int u)
{
    color[u] = GRAY;
    for (auto w:adj[u])
        if (color[w] == WHITE) DFS_visit(w);
    color[u] = BLACK;
    topological_sort.push(u);
}

void DFS()
{
    for (int i = 0; i < V; ++i)
        if (color[i] == WHITE) DFS_visit(i);
}
int main()
{
    fin >> V >> E;

    for (int i = 0; i < E; ++i)
    {
        fin >> x >> y;
        x--, y--;
        adj[x].push_back(y);
    }

    DFS();

    while (!topological_sort.empty())
    {
        fout << topological_sort.top() + 1 << " ";
        topological_sort.pop();
    }

    fin.close();
    fout.close();
    return 0;
}