Cod sursa(job #2062893)

Utilizator preda.andreiPreda Andrei preda.andrei Data 10 noiembrie 2017 22:01:59
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

struct Node
{
  int indegree = 0;
  vector<int> edges;
};

using Graph = vector<Node>;

vector<int> TopologicalSort(Graph &g)
{
  queue<int> q;
  for (size_t i = 0; i < g.size(); ++i) {
    if (g[i].indegree == 0) {
      q.push(i);
    }
  }

  vector<int> order;
  while (!q.empty()) {
    auto node = q.front();
    q.pop();

    order.push_back(node);

    for (const auto &next : g[node].edges) {
      g[next].indegree -= 1;
      if (g[next].indegree == 0) {
        q.push(next);
      }
    }
  }
  return order;
}

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

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

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

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

  return 0;
}