Cod sursa(job #2595071)

Utilizator avtobusAvtobus avtobus Data 7 aprilie 2020 00:02:02
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
// DFS (starting from the vertices with incoming degree = 0)
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < n; i++)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int INF = 0x3f3f3f3f;

ifstream fin ("sortaret.in");
ofstream fout ("sortaret.out");
const int Nmax = 50333;
vi G[Nmax];
vi res;
char vis[Nmax];

// int in_deg[Nmax];

void dfs(int nod) {
  vis[nod] = 1;
  for(auto y: G[nod]) {
    if(!vis[y]) {
      dfs(y);
    }
  }
  res.push_back(nod);
}

int main(void) {
  int N, M, x, y;
  fin >> N >> M;

  rep(i,N) { vis[i] = 0; }

  rep(i, M) {
    fin >> x >> y;
    --x, --y;
    G[x].push_back(y);
  }

  rep(i,N) {
    if(!vis[i]) { dfs(i); }
  }

  reverse(res.begin(), res.end());

  for(auto x: res) { fout << x+1 << ' '; }
  fout << endl;

  return 0;
}