Cod sursa(job #2604906)

Utilizator iuliap1999Iulia Popa iuliap1999 Data 23 aprilie 2020 20:40:36
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream f("sortaret.in");
ofstream g("sortaret.out");

const int NMAX = 5e4+5;
vector<int> graf[NMAX];
bool vis[NMAX];
vector <int> topSort;

void dfs(int nod) {
    vis[nod] = 1;
    for(int i = 0; i < (int)graf[nod].size(); i++) {
        int next = graf[nod][i];
        if(!vis[next]) {
            dfs(next);
        }
    }
    topSort.push_back(nod);
}
int main()
{
    int n, m;
    f >> n >> m;
    while(m--) {
        int x, y;
        f >> x >> y;
        graf[x].push_back(y);
    }
    for(int i = 1; i <= n; i++) {
        if(!vis[i]) {
            dfs(i);
        }
    }
    for(int i = topSort.size() - 1; i >= 0; i--) {
        g << topSort[i] << ' ';
    }
    return 0;
}