CSES - Shared codeLink to this code:
https://cses.fi/paste/7c23995417d5351d2b125b/
#include <bits/stdc++.h>
#define int long long
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
const int N = 2e5+5;
vector<int> adj[N];
int dfn[N], low[N], scc[N], inst[N], sccid, t, ans[N];
stack<int> st;
void dfs(int u){
dfn[u] = low[u] = ++t;
st.push(u);
inst[u] = 1;
for(auto v : adj[u]){
if(!dfn[v]){
dfs(v);
low[u] = min(low[u],low[v]);
}else if(inst[v]){
low[u] = min(low[u],dfn[v]);
}
}
if(dfn[u]==low[u]){
sccid++;
int x;
do{
x = st.top();
st.pop();
scc[x] = sccid;
inst[x] = 0;
}while(x!=u);
}
}
signed main(){
fastio
int n,m;
cin >> n >> m;
for(int i = 0;i < n;i++){
char a,b;
int x,y;
cin >> a >> x >> b >> y;
int aa,bb;
aa = (a=='+');
bb = (b=='+');
adj[x+n*(aa^1)].push_back(y+n*bb);
adj[y+n*(bb^1)].push_back(x+n*aa);
}
for(int i = 1;i <= m+n;i++){
if(!dfn[i]) dfs(i);
}
for(int i = 1;i <= m;i++){
if(scc[i]==scc[i+n]){
cout << "IMPOSSIBLE\n";
return 0;
}
}
for(int i = 1;i <= m;i++){
if(scc[i]<scc[i+n]) ans[i] = 0;
else ans[i] = 1;
}
for(int i = 1;i <= m;i++) cout << (ans[i] ? "+" : "-") << " ";
}