Cod sursa(job #2118084)

Utilizator raul044Moldovan Raul raul044 Data 29 ianuarie 2018 23:51:59
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

vector <int> v[50001], lista;
int s, n, m, color[50001];

void citire () {
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
    }
}
/// if there is any edge other than "tree", then the graph has at least a cycle
void dfs (int nod) {
    color[nod] = 1;
    int size = v[nod].size();
    for (int i = 0; i < size; ++i) {
        int y = v[nod][i];
        if (color[y] == 0) {
            //cout << nod << " " << y << " " << "tree" << '\n';
            dfs(y);
        }
    }
    color[nod] = 2;
    lista.push_back(nod);
}

int main () {
    citire();
    for (int i = 1; i <= n; ++i) {
        if (color[i] == 0) {
            dfs(i);
        }
    }
    int size = lista.size();
    for (int i = size-1; i >= 0; i--) {
        fout << lista[i] << " ";
    }
}