Pagini recente » Cod sursa (job #964665) | Cod sursa (job #3213998)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("sortaret.in");
ofstream fout("sortaret.out");
const int MAX_SIZE = 5 * 1e4;
int n, m;
vector<int> graph[MAX_SIZE + 1], inArches(MAX_SIZE + 1, 0), topologicalSorted;
vector<bool> visited(MAX_SIZE + 1, false);
void depthFirstSearch(int start) {
stack<int> nodes;
nodes.push(start);
while (!nodes.empty()) {
int currentNode = nodes.top();
nodes.pop();
if (!visited[currentNode]) {
visited[currentNode] = true;
topologicalSorted.push_back(currentNode);
for (int neighbor : graph[currentNode]) {
if (!visited[neighbor]) {
nodes.push(neighbor);
}
}
}
}
for (int node : topologicalSorted) {
fout << node << " ";
}
}
int main() {
fin >> n >> m;
for (int i = 0; i < m; ++i) {
int x, y;
fin >> x >> y;
graph[x].push_back(y);
++inArches[y];
}
int start = 1;
for (int i = 1; i <= n; ++i) {
if (inArches[i] == 0) {
start = i;
break;
}
}
depthFirstSearch(start);
return 0;
}