CSES - Shared codeLink to this code: https://cses.fi/paste/e731853f219a174da0ef31/
#include <bits/stdc++.h>
#define uwu return 0;
using namespace std;
const int SIZE = 2e5 + 5;
vector <pair<int, int>> graph[SIZE];
vector <int> path;
#define fs first
#define sc second
bool been[SIZE];
int in_deg[SIZE], out_deg[SIZE];
bool check_able(int V, int &out_nd){
int in_nd;
bool flag_found_in = 0, flag_found_out = 0;
for (int i = 1; i <= V; i++){
if(abs(out_deg[i] - in_deg[i]) >= 2)
return 0;
if(out_deg[i] - in_deg[i] == 1){
if(flag_found_out)
return 0;
flag_found_out = 1;
out_nd = i;
}
if(in_deg[i] - out_deg[i] == 1){
if(flag_found_in)
return 0;
flag_found_in = 1;
in_nd = i;
}
}
return (out_nd == 1 && in_nd == V);
}
int cur[SIZE];
void dfs(int nd){
for (; cur[nd] < graph[nd].size(); cur[nd]++){
if(!been[graph[nd][cur[nd]].sc]){
been[graph[nd][cur[nd]].sc] = 1;
dfs(graph[nd][cur[nd]].fs);
}
}
path.push_back(nd);
return;
}
int main(){
cin.tie(0), ios::sync_with_stdio(0);
int V, E;
cin >> V >> E;
for (int u, v, i = 0; i < E; i++){
cin >> u >> v;
graph[u].push_back({v, i});
in_deg[v]++;
out_deg[u]++;
}
// check the amount of odd nodes
int rt = 0;
if(!check_able(V, rt)){
cout << "IMPOSSIBLE\n";
uwu
}
// find path
dfs(rt);
reverse(path.begin(), path.end());
// check connectivity
if(path.size() != E + 1){
cout << "IMPOSSIBLE\n";
uwu
}
for(auto i:path){
cout << i << ' ';
}
cout << '\n';
uwu
}