Cod sursa(job #2062903)

Utilizator preda.andreiPreda Andrei preda.andrei Data 10 noiembrie 2017 22:06:57
Problema Sortare topologica Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <algorithm>
#include <fstream>
#include <numeric>
#include <vector>

using namespace std;

struct Node
{
  int exit_time = 0;
  vector<int> edges;

  constexpr bool Visited() const { return exit_time == 0; }
};

using Graph = vector<Node>;

void Dfs(Graph &g, int node)
{
  for (const auto &next : g[node].edges) {
    if (!g[next].Visited()) {
      Dfs(g, next);
    }
  }

  static int time = 0;
  g[node].exit_time = ++time;
}

vector<int> BuildOrder(Graph &g)
{
  vector<int> indexes(g.size());
  iota(indexes.begin(), indexes.end(), 0);

  auto great_times_first = [g] (int a, int b) -> bool {
    return g[a].exit_time > g[b].exit_time;
  };
  sort(indexes.begin(), indexes.end(), great_times_first);

  return indexes;
}

vector<int> TopologicalSort(Graph &g)
{
  for (size_t i = 0; i < g.size(); ++i) {
    if (!g[i].Visited()) {
      Dfs(g, i);
    }
  }
  return BuildOrder(g);
}

int main()
{
  ifstream fin("sortaret.in");
  ofstream fout("sortaret.out");

  int nodes, edges;
  fin >> nodes >> edges;

  Graph graph(nodes);
  for (int i = 0; i < nodes; ++i) {
    int x, y;
    fin >> x >> y;
    graph[x - 1].edges.push_back(y - 1);
  }

  auto order = TopologicalSort(graph);
  for (const auto &node : order) {
    fout << node + 1 << " ";
  }
  fout << "\n";

  return 0;
}