Cod sursa(job #2214996)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 20 iunie 2018 17:59:03
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int MAXN = 5e4;
const int MAXM = 1e5;

vector <int>g[MAXN + 1];
queue <int>nodes;
int n, m;
int grad[MAXN + 1];


int main() {
  in >> n >> m;

  for (int i = 1; i <= m; ++ i) {
    int x, y;
    in >> x >> y;
    g[x].push_back(y) ;
    ++ grad[y];
  }

  for (int i = 1; i <= n; ++ i)
    if (grad[i] == 0)
      nodes.push(i);

  while (nodes.size()) {
    for (auto x : g[nodes.front()]) {
      -- grad[x];
      if (grad[x] == 0)
        nodes.push(x);
    }
    out << nodes.front() << ' ';
    nodes.pop();
  }


  return 0;
}