Cod sursa(job #2543073)

Utilizator Horia14Horia Banciu Horia14 Data 10 februarie 2020 20:20:47
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include<fstream>
#include<iostream>
#include<vector>
#define MAX_VERTICES 50000
using namespace std;

vector<int>f;
vector<int>g[MAX_VERTICES + 1];
bool used[MAX_VERTICES + 1];
int n, m;

void readGraph() {
    int x, y;
    ifstream fin("sortaret.in");
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        fin >> x >> y;
        g[x].push_back(y);
    }
    fin.close();
}

void DFS(int node) {
    used[node] = 1;
    for(auto i : g[node]) {
        if(!used[i])
            DFS(i);
    }
    f.push_back(node);
}

void DFS_master() {
    for(int i = 1; i <= n; i++) {
        if(!used[i])
            DFS(i);
    }
}

void printTopologicalSort() {
    ofstream fout("sortaret.out");
    for(int i = f.size() - 1; i >= 0; i--)
        fout << f[i] << " ";
    fout << "\n";
    fout.close();
}

int main() {
    readGraph();
    DFS_master();
    printTopologicalSort();
    return 0;
}