Pagini recente » Clasament luni_ora_10.00 | Clasamentul arhivei educationale | Clasamentul arhivei educationale | Cod sursa (job #2985266) | Cod sursa (job #2062905)
#include <algorithm>
#include <fstream>
#include <numeric>
#include <vector>
using namespace std;
struct Node
{
int exit_time = 0;
vector<int> edges;
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;
}