Cod sursa(job #991215)

Utilizator toranagahVlad Badelita toranagah Data 30 august 2013 00:47:41
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.69 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <stack>
using namespace std;

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

const int MAX_N = 50100;

int N, M;
vector<int> graph[MAX_N];
bool visited[MAX_N];
stack<int> answer;

void dfs(int node);

int main() {
  fin >> N >> M;
  for (int i = 1, a, b; i <= M; ++i) {
    fin >> a >> b;
    graph[a].push_back(b);
  }

  for (int i = 1; i <= N; ++i) {
    if (!visited[i]) dfs(i);
  }
 
  while (!answer.empty()) {
    fout << answer.top() << ' ';
    answer.pop();
  }

  return 0;
}

void dfs(int node) {
  visited[node] = true;

  for (auto x : graph[node]) {
    if (!visited[x]) dfs(x);
  }

  answer.push(node);
}