Cod sursa(job #2174975)

Utilizator GoogalAbabei Daniel Googal Data 16 martie 2018 14:34:33
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>

using namespace std;

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

const int NMAX = 5 * 1e4;

int n, m;

bitset < 1 + NMAX > vis;
vector < int > g[1 + NMAX];
stack < int > st;

void dfs(int node) {
  vis[node] = 1;
  for(int i = 0; i < g[node].size(); i++) {
    int to = g[node][i];
    if(vis[to] == 0)
      dfs(to);
  }

  st.push(node);
}

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

  for(int i = 1; i <= n; i++)
    if(vis[i] == 0)
      dfs(i);

  while(!st.empty()) {
    out << st.top() << ' ';
    st.pop();
  }

  out << '\n';

  in.close();
  out.close();
  return 0;
}