Cod sursa(job #2555312)

Utilizator LazarRazvanLazar Razvan LazarRazvan Data 23 februarie 2020 21:23:59
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdio>
#include <vector>

#define NMAX 50001

using namespace std;

int v, e;       //nr of vertices, nr of edges
int visited[NMAX];

vector <int> graph[NMAX];
vector <int> solution;


void read();
void topologicalSort();
void DFS(int);
void write();

int main() {

    read();

    topologicalSort();

    write();

    return 0;
}

void read()
{
    freopen("sortaret.in", "r", stdin);

    scanf("%d%d", &v, &e);

    int x, y;
    for (int i = 1; i <= e; i++)
    {
        scanf("%d%d", &x, &y);

        graph[x].push_back(y);
    }
}

void topologicalSort()
{
    for (int i = 1; i <= v; i++)
    {
        if (visited[i] == 0)
        {
            DFS(i);
        }
    }
}

void DFS(int n)
{
    visited[n] = 1;

    for (unsigned int i = 0; i < graph[n].size(); i++)
    {
        int neighbour = graph[n][i];

        if (!visited[neighbour])
        {
            DFS(neighbour);
        }
    }

    solution.push_back(n);
}

void write()
{
    freopen("sortaret.out", "w", stdout);

    while(!solution.empty())
    {
        printf("%d ", solution.back());
        solution.pop_back();
    }

    fclose(stdout);
}