Pagini recente » Cod sursa (job #1012933) | Cod sursa (job #121004) | Cod sursa (job #2276340) | Cod sursa (job #1639927) | Cod sursa (job #2606427)
#include <bits/stdc++.h>
using namespace std;
#define NMAX 100009
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
int n;
int m;
vector<int> nodes[NMAX];
void read_input() {
ifstream fin("sortaret.in");
fin >> n >> m;
for (int i = 0; i < m; ++i) {
int x, y;
fin >> x >> y;
nodes[x].push_back(y);
}
fin.close();
}
vector<int> get_result() {
vector<int> topsort;
vector<bool> visited(n);
for (int i = 1; i <= n; ++i) {
if (!visited[i]) {
dfs(i, visited, topsort);
}
}
reverse(topsort.begin(), topsort.end());
return topsort;
}
void dfs(int node, vector<bool> &visited, vector<int> &topsort) {
visited[node] = true;
if (nodes[node].empty()) {
topsort.push_back(node);
return;
}
for (int i : nodes[node]) {
if (!visited[i])
dfs(i, visited, topsort);
}
topsort.push_back(node);
}
void print_output(vector<int> result) {
ofstream fout("sortaret.out");
int q = result.size();
for (int i = 0; i < q; ++i) {
fout << result[i] << ' ';
}
fout.close();
}
};
// Please always keep this simple main function!
int main() {
// Allocate a Task object on heap in order to be able to
// declare huge static-allocated data structures inside the class.
Task *task = new Task();
task->solve();
delete task;
return 0;
}