Cod sursa(job #2692619)

Utilizator avtobusAvtobus avtobus Data 3 ianuarie 2021 12:46:37
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < (int)(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");

int main(void) {
  // freopen("sortaret.in", "r", stdin);
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);
  int N, M, a,b;
  fin >> N >> M;
  vi d(N); // incoming degree
  vector<vi> g(N); // graph

  rep(i, M) {
    fin >> a >> b;
    --a, --b;
    g[a].push_back(b);
    d[b]++;
  }

  queue<int> Q;
  rep(i, N) {
    if (d[i] == 0) {
      Q.push(i);
    }
  }
  while(!Q.empty()) {
    auto x = Q.front(); Q.pop();
    fout << x + 1 << " ";
    for(auto y: g[x]) {
      d[y]--;
      if (d[y] == 0) {
        Q.push(y);
      }
    }
  }
  fout << "\n";

  return 0;
}