SAT and 3-CNF-SAT
Circuits are a convenient starting point, but most reductions are easier from formulas. This lesson takes the first two steps of the reduction chain: circuit satisfiability reduces to formula satisfiability (SAT), and SAT reduces to 3-CNF-SAT, satisfiability of formulas in conjunctive normal form with exactly three literals per clause. That rigid format is what makes 3-CNF-SAT the favourite source problem for gadget reductions. The lesson ends with a contrast: with two literals per clause the problem drops into P. The logic background is in Satisfiability of Discrete Mathematics.
Formulas and normal forms
A Boolean formula is built from variables , the connectives and parentheses. SAT asks whether a formula has a satisfying assignment. It is in NP (the assignment is the certificate; evaluating a formula takes polynomial time).
A literal is a variable or its negation. A formula is in conjunctive normal form (CNF) if it is an AND of clauses, each an OR of literals, and in 3-CNF if every clause has exactly three distinct literals, for example
CIRCUIT-SAT reduces to SAT
The obvious reduction, writing the circuit's output as one big formula, fails: a wire with fan-out 2 would copy its sub-formula twice, and repeated copying can blow the size up exponentially. The fix is to give every wire its own variable and write one small formula per gate stating that its output wire has the right value. For a gate this is . The formula is the AND of all gate formulas and the output variable:
Its size is linear in the circuit. If the circuit is satisfiable, setting each wire variable to its value in that evaluation satisfies . Conversely, a satisfying assignment of assigns every gate variable the value the gate really computes, and , so its input part satisfies the circuit. Since SAT is in NP, SAT is NP-complete.
Each gate formula also has a tiny CNF, which gives CNF directly (the Tseitin transformation): for the clauses , , ; for the clauses , , ; for the clauses , . The program applies it to the small circuit of Circuit Satisfiability and the Cook-Levin Idea and checks that the satisfying assignments of the formula, restricted to the circuit inputs, are exactly the circuit's.
from itertools import product
circuit = [("g1", "OR", ["x1", "x2"]), ("g2", "NOT", ["x3"]), ("g3", "AND", ["g1", "g2"]),
("g4", "AND", ["x1", "x2"]), ("g5", "NOT", ["g4"]), ("out", "AND", ["g3", "g5"])]
inputs = ["x1", "x2", "x3"]
def tseitin(circuit):
clauses = [] # literals: (name, True) or (name, False)
for c, kind, ins in circuit:
if kind == "AND":
a, b = ins
clauses += [[(c, False), (a, True)], [(c, False), (b, True)], [(c, True), (a, False), (b, False)]]
elif kind == "OR":
a, b = ins
clauses += [[(c, True), (a, False)], [(c, True), (b, False)], [(c, False), (a, True), (b, True)]]
else:
(a,) = ins
clauses += [[(c, True), (a, True)], [(c, False), (a, False)]]
clauses.append([("out", True)])
return clauses
clauses = tseitin(circuit)
variables = inputs + [name for name, _, _ in circuit]
print(len(clauses), "clauses over", len(variables), "variables")
sat_inputs = set()
for bits in product([False, True], repeat=len(variables)):
a = dict(zip(variables, bits))
if all(any(a[v] == sign for v, sign in cl) for cl in clauses):
sat_inputs.add(tuple(int(a[v]) for v in inputs))
print("satisfying assignments of the formula, on the inputs:", sorted(sat_inputs))17 clauses over 9 variables
satisfying assignments of the formula, on the inputs: [(0, 1, 0), (1, 0, 0)]
The formula's solutions on are and , the same as the circuit's.
SAT reduces to 3-CNF-SAT
Tseitin already yields a CNF formula with clauses of at most three literals. Two small repairs give exactly three distinct literals per clause:
- A clause with two literals becomes with a new variable : both are satisfied exactly when is.
- A clause with one literal becomes four clauses , , , , all satisfied exactly when is.
For a CNF formula with long clauses, a clause , , is split with new variables into the chain
which is satisfiable (by a choice of the 's) exactly when some is true. Every step multiplies the size by a constant, so the whole reduction is polynomial, and since 3-CNF-SAT is in NP, 3-CNF-SAT is NP-complete. The program implements the clause normalization and tests it on random CNF formulas against brute force.
import random
from itertools import product
def to_3cnf(clauses, n):
"""clauses: lists of nonzero ints (v or -v), variables 1..n; returns (3-CNF clauses, new n)"""
out = []
def fresh():
nonlocal n
n += 1
return n
for c in clauses:
c = list(dict.fromkeys(c)) # drop repeated literals
if len(c) == 1:
p, q = fresh(), fresh()
out += [[c[0], p, q], [c[0], p, -q], [c[0], -p, q], [c[0], -p, -q]]
elif len(c) == 2:
p = fresh()
out += [c + [p], c + [-p]]
elif len(c) == 3:
out.append(c)
else:
y = fresh()
out.append([c[0], c[1], y])
for lit in c[2:-2]:
y2 = fresh()
out.append([-y, lit, y2])
y = y2
out.append([-y, c[-2], c[-1]])
return out, n
def satisfiable(clauses, n):
return any(all(any((l > 0) == bits[abs(l) - 1] for l in c) for c in clauses)
for bits in product([False, True], repeat=n))
rng = random.Random(5)
agree = sat = 0
for trial in range(150):
n = 4
clauses = [[rng.choice([1, -1]) * rng.randint(1, n) for _ in range(rng.randint(1, 5))]
for _ in range(rng.randint(2, 7))]
clauses = [c for c in clauses if not any(-l in c for l in c)] # skip always-true clauses
new, m = to_3cnf(clauses, n)
assert all(len(c) == 3 and len({abs(l) for l in c}) == 3 for c in new)
s1, s2 = satisfiable(clauses, n), satisfiable(new, m)
agree += s1 == s2
sat += s1
print(f"150 random formulas: satisfiability preserved in {agree}; {sat} were satisfiable")
print("example:", to_3cnf([[1, -2, 3, 4, -5]], 5)[0])150 random formulas: satisfiability preserved in 150; 138 were satisfiable
example: [[1, -2, 6], [-6, 3, 7], [-7, 4, -5]]
Two literals per clause: easy
2-CNF-SAT is in P. A clause is equivalent to the two implications and . Build the implication graph with a vertex for every literal and these edges for every clause. The formula is unsatisfiable exactly when some variable and its negation lie in the same strongly connected component (each implies the other); otherwise, setting each variable true iff its positive literal's component comes later in a topological order of the components gives a satisfying assignment. Strongly connected components take linear time (Kosaraju's Algorithm), so 2-SAT is solved in . Going from two literals to three is the jump from linear time to NP-complete.
In C++
2-SAT with Kosaraju's algorithm on the implication graph. Literal is vertex and is .
#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>
struct TwoSat {
int n;
std::vector<std::vector<int>> g, gr;
explicit TwoSat(int vars) : n(vars), g(2 * vars), gr(2 * vars) {}
static int lit(int v, bool positive) { return 2 * v + (positive ? 0 : 1); }
void add_clause(int a, int b) { // (a OR b) gives NOT a -> b and NOT b -> a
g[a ^ 1].push_back(b); g[b ^ 1].push_back(a);
gr[b].push_back(a ^ 1); gr[a].push_back(b ^ 1);
}
bool solve(std::vector<bool>& value) {
int N = 2 * n;
std::vector<int> order, comp(N, -1);
std::vector<bool> seen(N, false);
std::function<void(int)> dfs1 = [&](int u) {
seen[u] = true;
for (int v : g[u]) if (!seen[v]) dfs1(v);
order.push_back(u);
};
std::function<void(int, int)> dfs2 = [&](int u, int c) {
comp[u] = c;
for (int v : gr[u]) if (comp[v] < 0) dfs2(v, c);
};
for (int u = 0; u < N; u++) if (!seen[u]) dfs1(u);
int c = 0;
for (int i = N - 1; i >= 0; i--) if (comp[order[i]] < 0) dfs2(order[i], c++);
value.assign(n, false);
for (int v = 0; v < n; v++) {
if (comp[2 * v] == comp[2 * v + 1]) return false;
value[v] = comp[2 * v] > comp[2 * v + 1]; // components are numbered in topological order
}
return true;
}
};
int main() {
// (x0 or x1) (not x0 or x2) (not x1 or not x2) (x1 or x2)
TwoSat s(3);
s.add_clause(TwoSat::lit(0, true), TwoSat::lit(1, true));
s.add_clause(TwoSat::lit(0, false), TwoSat::lit(2, true));
s.add_clause(TwoSat::lit(1, false), TwoSat::lit(2, false));
s.add_clause(TwoSat::lit(1, true), TwoSat::lit(2, true));
std::vector<bool> val;
if (s.solve(val)) std::printf("satisfiable: x0 = %d, x1 = %d, x2 = %d\n", int(val[0]), int(val[1]), int(val[2]));
s.add_clause(TwoSat::lit(0, false), TwoSat::lit(1, true)); // add (not x0 or x1)
std::printf("with (not x0 or x1): %s\n", s.solve(val) ? "satisfiable" : "unsatisfiable");
s.add_clause(TwoSat::lit(0, true), TwoSat::lit(1, false)); // and (x0 or not x1): forces x0 = x1
std::printf("with (x0 or not x1) too: %s\n", s.solve(val) ? "satisfiable" : "unsatisfiable");
}satisfiable: x0 = 1, x1 = 0, x2 = 1
with (not x0 or x1): satisfiable
with (x0 or not x1) too: unsatisfiable
With forced, the first clause makes both true, then and contradict each other, so some variable and its negation end up in one strongly connected component.
Test yourself
Why does the reduction from CIRCUIT-SAT to SAT introduce a variable for every wire?
- To make the formula shorter than the circuit
- Because expanding shared sub-circuits into one formula can blow up its size exponentially
- Because SAT needs at least variables
- Because circuits have no variables
How is the clause turned into 3-CNF?
- with a new variable
- It cannot be
Which of these problems is known to be in P?
- SAT
- 3-CNF-SAT
- 2-CNF-SAT
- CIRCUIT-SAT
Into how many 3-literal clauses does the chain construction split a clause with literals?
- 2
- 3
- 4
- 6