Pagini recente » Cod sursa (job #2970989) | Cod sursa (job #2329795) | Cod sursa (job #2325623) | Cod sursa (job #2744322) | Cod sursa (job #3228996)
#include <bits/stdc++.h>
using namespace std;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
// numarul maxim de noduri
static constexpr int NMAX = (int)1e5 + 5; // 10^5 + 5 = 100.005
// n = numar de noduri, m = numar de muchii/arce
int n, m;
// adj[node] = lista de adiacenta a nodului node
// exemplu: daca adj[node] = {..., neigh, ...} => exista arcul (node, neigh)
vector<int> adj[NMAX];
void read_input() {
ifstream fin("sortaret.in");
fin >> n >> m;
for (int i = 1, x, y; i <= m; i++) {
fin >> x >> y; // arc (x, y)
adj[x].push_back(y);
}
fin.close();
}
void dfs(int node, vector<int>& start, vector<int>& end, int& timestamp) {
start[node] = timestamp;
timestamp++;
for (int neigh : adj[node]) {
if (start[neigh] == 0) {
start[neigh] = timestamp;
dfs(neigh, start, end, timestamp);
end[neigh] = timestamp;
timestamp++;
}
}
end[node] = timestamp;
}
vector<int> get_result() {
// TODO: Faceti sortarea topologica a grafului stocat cu liste de adiacenta din adj.
// *******
// ATENTIE: nodurile sunt indexate de la 1 la n.
// *******
vector<int> topsort;
vector<int> start(n + 1, 0);
vector<int> end(n + 1, 0);
int time = 1;
for (int i = 1; i <= n; i++) {
if (start[i] == 0) {
dfs(i, start, end, time);
}
}
// for (int i = 1; i <= n; i++) {
// cout << "i = " << i << " - " << end[i] << "\n";
// }
// cout << "\n";
vector<int> nodes(n + 1);
for (int i = 1; i <= n; i++) {
nodes[i] = i;
}
// Sortarea topologica va fi facuta in ordinea descrescatoare a
// timpului de finalizare a DFS-ului.
sort(nodes.begin() + 1, nodes.end(), [&](int a, int b) { return end[a] > end[b]; });
for (int i = 1; i <= n; i++) {
topsort.push_back(nodes[i]);
}
return topsort;
}
void print_output(const vector<int>& topsort) {
ofstream fout("sortaret.out");
for (auto node : topsort) {
fout << node << ' ';
}
fout << '\n';
fout.close();
}
};
// [ATENTIE] NU modifica functia main!
int main() {
// * se aloca un obiect Task pe heap
// (se presupune ca e prea mare pentru a fi alocat pe stiva)
// * se apeleaza metoda solve()
// (citire, rezolvare, printare)
// * se distruge obiectul si se elibereaza memoria
auto* task = new (nothrow) Task(); // hint: cppreference/nothrow
if (!task) {
cerr << "new failed: WTF are you doing? Throw your PC!\n";
return -1;
}
task->solve();
delete task;
return 0;
}