| # | Time | Username | Problem | Language | Result | Execution time | Memory |
|---|---|---|---|---|---|---|---|
| 1359475 | opeleklanos | Thousands Islands (IOI22_islands) | C++20 | 0 ms | 0 KiB |
#include <iostream>
#include <vector>
#include <variant>
#include <algorithm>
#include <stack>
using namespace std;
vector<vector<pair<int, int>>> adj;
vector<int> vis;
vector<int> tpsort;
vector<int> path;
stack<int> s;
int findPath(int st){
if(vis[st]){
vector<int> nodesInCycle;
while(s.top() != st) nodesInCycle.push_back(s.top());
int curr = st;
path.push_back(st);
for(auto i : nodesInCycle){
path.push_back(i);
}
path.push_back(st);
for(auto i : nodesInCycle){
path.push_back(i);
}
path.push_back(st);
reverse(nodesInCycle.begin(), nodesInCycle.end());
for(auto i : nodesInCycle) path.push_back(i);
path.push_back(st);
for(auto i : nodesInCycle) path.push_back(i);
path.push_back(st);
return 1;
}
vis[st] = 1;
s.push(st);
path.push_back(st);
int found = 0;
for(auto i : adj[st]) if(findPath(st)) found = 1;
if(!found) path.pop_back();
else path.push_back(st);
s.pop();
return found;
}
void dfs(int st){
vis[st] = 1;
for(auto c : adj[st]) if(!vis[c.first]) dfs(c.first);
tpsort.push_back(st);
}
vector<int> buildPath(){
vector<int> ret;
for(int i = 0; i<path.size()-1; i++){
int f = 0;
for(int j = 0; j<adj[path[i]].size(); j++){
if(adj[path[i]][j].first == path[i+1] && adj[path[i]][j].second > 0){
ret.push_back(adj[path[i]][j].second);
adj[path[i]][j].second = -adj[path[i]][j].second;
f = 1;
break;
}
}
if(f == 1) continue;
for(int j = 0; j<adj[path[i+1]].size(); j++){
if(adj[path[i+1]][j].first == path[i] && adj[path[i]][j].second < 0){
ret.push_back(-adj[path[i+1]][j].second);
adj[path[i+1]][j].second = -adj[path[i+1]][j].second;
f = 1;
break;
}
}
}
return ret;
}
variant<bool, vector<int>> find_journey(int N, int M, vector<int> U, vector<int> V){
adj.assign(N, {});
vis.assign(N, 0);
tpsort.assign(0, 0);
goesTo.assign()
for(int i = 0; i<M; i++){
adj[U[i]].push_back({V[i], i});
}
dfs(0);
reverse(tpsort.begin(), tpsort.end());
vector<int> indx(N, -1);
for(int i = 0; i<tpsort.size(); i++) indx[tpsort[i]] = i;
for(int i = 0; i<N; i++){
if(!vis[i]) continue;
for(auto j : adj[i]){
if(indx[i] > indx[j.first]){
path.assign(0, 0);
vis.assign(N, 0);
findPath(0);
return buildPath();
}
}
}
return (bool)0;
}