Pagini recente » Cod sursa (job #453952) | Profil M@2Te4i | Cod sursa (job #388518) | Cod sursa (job #1998912) | Cod sursa (job #2062893)
#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;
}