CSES Problem Set Course Schedule Solution
Problem Link: https://cses.fi/problemset/task/1679
Solution in C++:
/// La ilaha illellahu muhammadur rasulullah
///******Bismillahir-Rahmanir-Rahim******///
/// Abul Hasnat Tonmoy
/// Department of CSE,23rd batch
/// Islamic University,Bangladesh
///**********ALLAH IS ALMIGHTY************///
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
std::vector<int> g[N];
vector<int> ans;
bool cycle;
int col[N];
void dfs(int u) {
col[u] = 1;
for (auto v : g[u]) {
if (col[v] == 0) {
dfs(v);
} else if (col[v] == 1)
cycle = true;
}
col[u] = 2;
ans.push_back(u);
}
int main() {
int n, e;
cin >> n >> e;
while (e--) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
}
cycle = false;
for (int i = 1; i <= n; i++) {
if (col[i] == 0) dfs(i);
}
if (cycle == true)
cout << "IMPOSSIBLE" << endl;
else {
reverse(ans.begin(), ans.end());
for (auto i : ans) {
cout << i << " ";
}
cout << endl;
}
}
No comments