TExcelTAD

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 x1,…,xnx_1, \ldots, x_n, the connectives ∧,∨,¬,→,↔\land, \lor, \lnot, \to, \leftrightarrow 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

(x1∨¬x2∨x3)∧(¬x1∨x2∨x4)∧(x2∨¬x3∨¬x4).(x_1 \lor \lnot x_2 \lor x_3) \land (\lnot x_1 \lor x_2 \lor x_4) \land (x_2 \lor \lnot x_3 \lor \lnot x_4).

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 xc=xa∧xbx_c = x_a \land x_b this is xc↔(xa∧xb)x_c \leftrightarrow (x_a \land x_b). The formula is the AND of all gate formulas and the output variable:

ϕ=xout∧⋀gates g(xg↔gateg(its input wires)).\phi = x_{\text{out}} \land \bigwedge_{\text{gates } g} \bigl(x_g \leftrightarrow \text{gate}_g(\text{its input wires})\bigr).

Its size is linear in the circuit. If the circuit is satisfiable, setting each wire variable to its value in that evaluation satisfies ϕ\phi. Conversely, a satisfying assignment of ϕ\phi assigns every gate variable the value the gate really computes, and xout=1x_\text{out} = 1, 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 c↔(a∧b)c \leftrightarrow (a \land b) the clauses (¬c∨a)(\lnot c \lor a), (¬c∨b)(\lnot c \lor b), (c∨¬a∨¬b)(c \lor \lnot a \lor \lnot b); for c↔(a∨b)c \leftrightarrow (a \lor b) the clauses (c∨¬a)(c \lor \lnot a), (c∨¬b)(c \lor \lnot b), (¬c∨a∨b)(\lnot c \lor a \lor b); for c↔¬ac \leftrightarrow \lnot a the clauses (c∨a)(c \lor a), (¬c∨¬a)(\lnot c \lor \lnot a). 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.

python · try it yourself
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 x1,x2,x3x_1, x_2, x_3 are (0,1,0)(0, 1, 0) and (1,0,0)(1, 0, 0), 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 (ℓ1∨ℓ2)(\ell_1 \lor \ell_2) becomes (ℓ1∨ℓ2∨p)∧(ℓ1∨ℓ2∨¬p)(\ell_1 \lor \ell_2 \lor p) \land (\ell_1 \lor \ell_2 \lor \lnot p) with a new variable pp: both are satisfied exactly when ℓ1∨ℓ2\ell_1 \lor \ell_2 is.
  • A clause with one literal (ℓ)(\ell) becomes four clauses (ℓ∨p∨q)(\ell \lor p \lor q), (ℓ∨p∨¬q)(\ell \lor p \lor \lnot q), (ℓ∨¬p∨q)(\ell \lor \lnot p \lor q), (ℓ∨¬p∨¬q)(\ell \lor \lnot p \lor \lnot q), all satisfied exactly when ℓ\ell is.

For a CNF formula with long clauses, a clause (ℓ1∨ℓ2∨⋯∨ℓk)(\ell_1 \lor \ell_2 \lor \cdots \lor \ell_k), k>3k > 3, is split with new variables y1,…,yk−3y_1, \ldots, y_{k-3} into the chain

(ℓ1∨ℓ2∨y1)∧(¬y1∨ℓ3∨y2)∧⋯∧(¬yk−3∨ℓk−1∨ℓk),(\ell_1 \lor \ell_2 \lor y_1) \land (\lnot y_1 \lor \ell_3 \lor y_2) \land \cdots \land (\lnot y_{k-3} \lor \ell_{k-1} \lor \ell_k),

which is satisfiable (by a choice of the yy's) exactly when some ℓi\ell_i 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.

python · try it yourself
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 (a∨b)(a \lor b) is equivalent to the two implications ¬a→b\lnot a \to b and ¬b→a\lnot b \to a. Build the implication graph with a vertex for every literal and these edges for every clause. The formula is unsatisfiable exactly when some variable xx 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 O(n+m)O(n + m). 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 xix_i is vertex 2i2i and ¬xi\lnot x_i is 2i+12i + 1.

cpp · try it yourself
#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 x0=x1x_0 = x_1 forced, the first clause makes both true, then x0→x2x_0 \to x_2 and x1→¬x2x_1 \to \lnot x_2 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?

  1. To make the formula shorter than the circuit
  2. Because expanding shared sub-circuits into one formula can blow up its size exponentially
  3. Because SAT needs at least nn variables
  4. Because circuits have no variables

How is the clause (ℓ1∨ℓ2)(\ell_1 \lor \ell_2) turned into 3-CNF?

  1. (ℓ1∨ℓ2∨ℓ2)(\ell_1 \lor \ell_2 \lor \ell_2)
  2. (ℓ1∨ℓ2∨p)∧(ℓ1∨ℓ2∨¬p)(\ell_1 \lor \ell_2 \lor p) \land (\ell_1 \lor \ell_2 \lor \lnot p) with a new variable pp
  3. (ℓ1∨p∨q)(\ell_1 \lor p \lor q)
  4. It cannot be

Which of these problems is known to be in P?

  1. SAT
  2. 3-CNF-SAT
  3. 2-CNF-SAT
  4. CIRCUIT-SAT

Into how many 3-literal clauses does the chain construction split a clause with k=6k = 6 literals?

  1. 2
  2. 3
  3. 4
  4. 6