This documentation is automatically generated by online-judge-tools/verification-helper
#include "graph/twosat.hpp"定义于头文件 twosat.hpp
struct TwoSat;
维护 $n$ 个布尔变量 $x_0, \dots, x_{n-1}$ 上的 2-SAT 子句,并求出一组可满足解。
构造
| 成员函数 | 说明 |
|---|---|
TwoSat(int n) |
构造 $n$ 个无约束变量,$O(n)$ |
修改
| 成员函数 | 说明 |
|---|---|
void addClause(int u, bool f, int v, bool g) |
加入子句 $(x_u = f) \lor (x_v = g)$,$O(1)$ |
void set(int u, bool f) |
加入子句 $(x_u = f)$,$O(1)$ |
void implies(int u, bool f, int v, bool g) |
加入蕴含 $(x_u = f) \Rightarrow (x_v = g)$,$O(1)$ |
查询
| 成员函数 | 说明 |
|---|---|
pair<bool, vector<int>> satisfiable() |
求一组赋值,$O(n + m)$ |
satisfiable() 返回 {ok, ans}:ok 为子句集是否可满足,ans[i] 为 $x_i$ 的取值(1 为真、0 为假),ok 为 false 时 ans 为空。
$n$ 为变量数,$m$ 为加入的子句条数。
TwoSat ts(n);
ts.addClause(0, true, 1, false);
ts.set(2, true);
ts.implies(0, true, 1, true);
auto [ok, ans] = ts.satisfiable();
#pragma once
#include <graph/components/scc.hpp>
struct TwoSat {
int n;
Digraph<int> graph;
vector<int> ans;
TwoSat(int n_) : n(n_), graph(2 * n), ans(n) {}
// add clause: (x_u = f) ∨ (x_v = g)
void addClause(int u, bool f, int v, bool g) {
graph.add(2 * u + !f, 2 * v + g);
graph.add(2 * v + !g, 2 * u + f);
}
// (x_u = f)
void set(int u, bool f) {
addClause(u, f, u, f);
}
// (x_u = f) -> (x_v = g)
void implies(int u, int f, int v, int g) {
addClause(u, !f, v, g);
}
pair<bool, vector<int>> satisfiable() {
auto [cnt, id] = SCC(graph);
for (int i = 0; i < n; i++) {
if (id[2 * i] == id[2 * i + 1]) {
return {false, {}};
}
ans[i] = id[2 * i] < id[2 * i + 1];
}
return {true, ans};
}
};