Cod sursa(job #3134092)

Utilizator ggaaggaabbiigoteciuc gabriel ggaaggaabbii Data 28 mai 2023 14:24:34
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.62 kb
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
#define MAXN 50010
ifstream f("sortaret.in");
ofstream g("sortaret.out");
vector<int> G[MAXN];
int v[MAXN], viz[MAXN], n, m, x, y, k;

void dfs(int nod) {
    viz[nod] = 1;
    for (auto it:G[nod]) {
        if (!viz[it]) {
            dfs(it);
        }
    }
    v[++k] = nod;
}

int main() {
  f >> n >> m;
  while (m--) {
    f >> x >> y;
    G[x].push_back(y);
  }

  for (int i = 1; i <= n; ++i) {
    if (!viz[i]) {
        dfs(i);
    }
  }

  for (int i = n; i >= 1; --i)
    g << v[i] << ' ';
  return 0;
}