This documentation is automatically generated by competitive-verifier/competitive-verifier
#include "other/two_sat.hpp"2-SAT solver using strongly connected components. Variables are represented
as integers $0$ to $n-1$, with bitwise not representing negation (~x is $\neg
x$).
TwoSAT(int n)
n variablesvoid add_if(int x, int y)
void add_or(int x, int y)
void add_nand(int x, int y)
void set_true(int x)
void set_false(int x)
vector<bool> run()
#pragma once
#include "../graph/scc.hpp"
struct TwoSAT {
int n;
vector<basic_string<int>> g;
TwoSAT(int _n) : n(_n), g(2 * n) {}
void add_if(int x, int y) { g[ev(x)] += ev(y), g[ev(~y)] += ev(~x); }
void add_or(int x, int y) { add_if(~x, y); }
void add_nand(int x, int y) { add_if(x, ~y); }
void set_true(int x) { add_if(~x, x); }
void set_false(int x) { add_if(x, ~x); }
vector<bool> run() {
vector<bool> res(n);
auto [scc, rep, gd] = condense(g);
for (int i = 0; i < n; i++) {
if (rep[i] == rep[i + n]) return {};
res[i] = rep[i] > rep[i + n];
}
return res;
}
int ev(int x) { return x < 0 ? ~x + n : x; }
};
#line 2 "other/two_sat.hpp"
#line 2 "graph/scc.hpp"
template<class G> auto find_scc(const G &g) {
int n = (int)g.size();
vector<int> val(n), z;
vector<char> added(n);
vector<basic_string<int>> scc;
int time = 0;
auto dfs = [&](auto &self, int v) -> int {
int low = val[v] = time++;
z.push_back(v);
for (auto u : g[v])
if (!added[u]) low = min(low, val[u] ?: self(self, u));
if (low == val[v]) {
scc.emplace_back();
int x;
do {
x = z.back(), z.pop_back();
added[x] = true;
scc.back().push_back(x);
} while (x != v);
}
return val[v] = low;
};
for (int i = 0; i < n; i++)
if (!added[i]) dfs(dfs, i);
reverse(begin(scc), end(scc));
return scc;
}
template<class G> auto condense(const G &g) {
auto scc = find_scc(g);
int n = (int)scc.size();
vector<int> rep(g.size());
for (int i = 0; i < n; i++)
for (auto v : scc[i]) rep[v] = i;
vector<basic_string<int>> gd(n);
for (int v = 0; v < g.size(); v++)
for (auto u : g[v])
if (rep[v] != rep[u]) gd[rep[v]].push_back(rep[u]);
for (auto &v : gd) {
sort(begin(v), end(v));
v.erase(unique(begin(v), end(v)), end(v));
}
return make_tuple(move(scc), move(rep), move(gd));
}
#line 4 "other/two_sat.hpp"
struct TwoSAT {
int n;
vector<basic_string<int>> g;
TwoSAT(int _n) : n(_n), g(2 * n) {}
void add_if(int x, int y) { g[ev(x)] += ev(y), g[ev(~y)] += ev(~x); }
void add_or(int x, int y) { add_if(~x, y); }
void add_nand(int x, int y) { add_if(x, ~y); }
void set_true(int x) { add_if(~x, x); }
void set_false(int x) { add_if(x, ~x); }
vector<bool> run() {
vector<bool> res(n);
auto [scc, rep, gd] = condense(g);
for (int i = 0; i < n; i++) {
if (rep[i] == rep[i + n]) return {};
res[i] = rep[i] > rep[i + n];
}
return res;
}
int ev(int x) { return x < 0 ? ~x + n : x; }
};