Cod sursa(job #2721906)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 12 martie 2021 13:50:46
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int NMax = 5 * 1e4;

vector <int> g[NMax + 5], ans;
int n, m;
bool use[NMax + 5];

void Read(){
    fin >> n >> m;
    while (m--){
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
    }
}

void DFS(int node){
    use[node] = 1;
    for (auto ngh : g[node])
        if (!use[ngh])
            DFS(ngh);
    ans.push_back(node);
}

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

void Print(){
    for (int i = ans.size() - 1; i >= 0; i--)
        fout << ans[i] << ' ';
    fout << '\n';
}

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