TExcelTAD
Home › Parameterized & Fine-Grained Complexity › Mini Project: A Vertex Cover Solver with a Kernel and Branching

Mini Project: A Vertex Cover Solver with a Kernel and Branching

The first half of the course gave three tools for kk-VERTEX COVER: reduction rules and kernels, bounded search trees, and smarter branching. Real solvers combine all three and apply the rules again at every node of the search tree. In this project you build such a solver step by step, check it against brute force on seeded random graphs, and measure what each ingredient contributes by counting search-tree nodes.

The steps:

  1. Instances and a brute-force reference.
  2. Reduction rules: isolated vertices, degree 1, Buss's high-degree rule, and domination.
  3. Branching on a vertex of maximum degree, with paths and cycles solved exactly.
  4. The full solver: rules at every node plus branching, compared with plain edge branching and brute force.
  5. Scaling: large sparse graphs where brute force is hopeless.
  6. Port the solver to C++.

Each step is a complete program; later steps repeat the pieces they need.

Step 1: Instances and a reference

A test instance needs a known answer. Two generators: dense-ish random graphs G(n,p)G(n, p), small enough for brute force, and graphs with a planted cover of size kk (every edge touches the planted set), which gives an upper bound OPT≤k\text{OPT} \le k even for large nn. Brute force tries all vertex subsets by increasing size.

python · try it yourself
import random
from itertools import combinations

def gnp(n, p, seed):
    rng = random.Random(seed)
    adj = {v: set() for v in range(n)}
    for a, b in combinations(range(n), 2):
        if rng.random() < p:
            adj[a].add(b); adj[b].add(a)
    return adj

def planted(n, k, extra_deg, seed):
    rng = random.Random(seed)
    cover = rng.sample(range(n), k)
    adj = {v: set() for v in range(n)}
    for c in cover:
        for v in rng.sample(range(n), extra_deg):
            if v != c:
                adj[c].add(v); adj[v].add(c)
    return adj, set(cover)

def brute_force(adj):
    V = sorted(adj)
    E = [(a, b) for a in V for b in adj[a] if a < b]
    tried = 0
    for s in range(len(V) + 1):
        for S in combinations(V, s):
            tried += 1
            S = set(S)
            if all(a in S or b in S for a, b in E):
                return s, tried

for seed in range(3):
    G = gnp(14, 0.3, seed)
    opt, tried = brute_force(G)
    print(f"G(14, 0.3) seed {seed}: {sum(map(len, G.values())) // 2} edges, OPT = {opt}, {tried} subsets tried")
G, C = planted(200, 8, 6, seed=1)
E = [(a, b) for a in G for b in G[a] if a < b]
print(f"planted: 200 vertices, {len(E)} edges, planted cover of size {len(C)} valid:",
      all(a in C or b in C for a, b in E))
G(14, 0.3) seed 0: 17 edges, OPT = 5, 3072 subsets tried
G(14, 0.3) seed 1: 26 edges, OPT = 7, 6712 subsets tried
G(14, 0.3) seed 2: 20 edges, OPT = 6, 3600 subsets tried
planted: 200 vertices, 46 edges, planted cover of size 8 valid: True

Step 2: Reduction rules

Four safe rules, each justified in the course:

  • Isolated: delete a vertex of degree 0.
  • Degree 1: if vv has the single neighbour uu, put uu in the cover (Bounded Search Trees for Vertex Cover).
  • High degree (Buss): if deg⁡(v)>k\deg(v) > k, put vv in the cover (Kernels and Buss's Rule for Vertex Cover).
  • Domination: if uu and vv are adjacent and N[u]⊆N[v]N[u] \subseteq N[v] (closed neighbourhoods), put vv in the cover. Why: a cover avoiding vv contains all of N(v)N(v), which includes N[u]∖{v}∋uN[u] \setminus \{v\} \ni u; swapping uu for vv keeps it a cover of the same size. The degree-1 rule is the special case N[u]={u,v}N[u] = \{u, v\}.

After the rules, if more than k2k^2 edges remain the answer is NO. The program applies the rules exhaustively and reports how much of each graph survives.

python · try it yourself
import random
from itertools import combinations

def core_and_hubs(n, core, p, hubs, seed):
    """a random core G(core, p) plus hubs in the core carrying many pendant leaves"""
    rng = random.Random(seed)
    adj = {v: set() for v in range(n)}
    for a in range(core):
        for b in range(a + 1, core):
            if rng.random() < p:
                adj[a].add(b); adj[b].add(a)
    for h in rng.sample(range(core), hubs):
        for v in rng.sample(range(core, n), rng.randint(30, 80)):
            adj[h].add(v); adj[v].add(h)
    return adj

def take(adj, v):
    for u in adj.pop(v):
        adj[u].discard(v)

def reduce(adj, k, counts):
    adj = {v: set(nb) for v, nb in adj.items()}
    forced = []
    changed = True
    while changed and k >= 0:
        changed = False
        for v in sorted(adj):
            if v not in adj:
                continue
            d = len(adj[v])
            if d == 0:
                del adj[v]; counts["isolated"] += 1; changed = True
            elif d == 1:
                u = next(iter(adj[v]))
                take(adj, u); forced.append(u); k -= 1; counts["degree-1"] += 1; changed = True
            elif d > k:
                take(adj, v); forced.append(v); k -= 1; counts["buss"] += 1; changed = True
            else:
                closed_v = adj[v] | {v}
                u = next((u for u in sorted(adj[v]) if adj[u] | {u} <= closed_v), None)
                if u is not None:                  # N[u] inside N[v]: take v
                    take(adj, v); forced.append(v); k -= 1; counts["domination"] += 1; changed = True
            if k < 0:
                return None, k, forced
    m = sum(map(len, adj.values())) // 2
    if m > k * k:
        return None, k, forced
    return adj, k, forced

for seed in range(4):
    G = core_and_hubs(300, 24, 0.2, 4, seed)
    counts = {"isolated": 0, "degree-1": 0, "buss": 0, "domination": 0}
    K, k2, forced = reduce(G, 15, counts)
    m0 = sum(map(len, G.values())) // 2
    if K is None:
        print(f"seed {seed}: {m0} edges -> NO")
    else:
        print(f"seed {seed}: {m0} edges -> kernel {len(K)} vertices, {sum(map(len, K.values())) // 2} edges,"
              f" k' = {k2}, rules {counts}")
seed 0: 272 edges -> kernel 4 vertices, 4 edges, k' = 3, rules {'isolated': 284, 'degree-1': 4, 'buss': 4, 'domination': 4}
seed 1: 302 edges -> kernel 8 vertices, 11 edges, k' = 4, rules {'isolated': 281, 'degree-1': 2, 'buss': 4, 'domination': 5}
seed 2: 273 edges -> kernel 0 vertices, 0 edges, k' = 0, rules {'isolated': 285, 'degree-1': 4, 'buss': 4, 'domination': 7}
seed 3: 321 edges -> kernel 0 vertices, 0 edges, k' = 1, rules {'isolated': 286, 'degree-1': 4, 'buss': 4, 'domination': 6}

The test graphs are a random core of 24 vertices with four hubs carrying many pendant leaves. With k=15k = 15, Buss's rule removes the four hubs, their leaves become isolated, and degree-1 and domination finish most of the random core: from about 300 edges at most a dozen remain.

Step 3: Branching on maximum degree

On a reduced graph, branch on a vertex vv of maximum degree: either vv is in the cover, or all of N(v)N(v) is. If the maximum degree is at most 2, the graph is a union of paths and cycles, solved exactly (Branching Vectors and a Faster Vertex Cover). The program compares this branching (without reduction rules) against plain edge branching on small random graphs, both checked against brute force.

python · try it yourself
import random
from itertools import combinations

def gnp(n, p, seed):
    rng = random.Random(seed)
    adj = {v: set() for v in range(n)}
    for a, b in combinations(range(n), 2):
        if rng.random() < p:
            adj[a].add(b); adj[b].add(a)
    return adj

def without(adj, S):
    return {v: nb - S for v, nb in adj.items() if v not in S}

def paths_and_cycles(adj):
    seen, total = set(), 0
    for s in adj:
        if s in seen or not adj[s]:
            continue
        comp, stack = [], [s]
        seen.add(s)
        while stack:
            x = stack.pop(); comp.append(x)
            for y in adj[x]:
                if y not in seen:
                    seen.add(y); stack.append(y)
        edges = sum(len(adj[x]) for x in comp) // 2
        total += (len(comp) + 1) // 2 if edges == len(comp) else len(comp) // 2
    return total

def edge_branch(adj, k, st):
    st[0] += 1
    e = next(((u, v) for u in adj for v in adj[u]), None)
    if e is None:
        return True
    if k <= 0:
        return False
    return edge_branch(without(adj, {e[0]}), k - 1, st) or edge_branch(without(adj, {e[1]}), k - 1, st)

def degree_branch(adj, k, st):
    st[0] += 1
    if k < 0:
        return False
    v = max(adj, key=lambda x: (len(adj[x]), -x), default=None)
    if v is None or not adj[v]:
        return True
    if len(adj[v]) <= 2:
        return paths_and_cycles(adj) <= k
    return degree_branch(without(adj, {v}), k - 1, st) or degree_branch(without(adj, adj[v] | {v}), k - len(adj[v]), st)

def opt(adj):
    E = [(a, b) for a in adj for b in adj[a] if a < b]
    for s in range(len(adj) + 1):
        for S in combinations(adj, s):
            if all(a in S or b in S for a, b in E):
                return s

print("seed  OPT  edge-branch nodes  degree-branch nodes  correct")
for seed in range(5):
    G = gnp(18, 0.25, seed)
    o = opt(G)
    a, b = [0], [0]
    ra = (edge_branch(G, o - 1, a), edge_branch(G, o, a))
    rb = (degree_branch(G, o - 1, b), degree_branch(G, o, b))
    print(f"{seed:4} {o:4} {a[0]:18} {b[0]:20}  {ra == rb == (False, True)}")
seed  OPT  edge-branch nodes  degree-branch nodes  correct
   0    9               1500                   30  True
   1   11               3069                   30  True
   2   10               2043                   46  True
   3   10               1823                   20  True
   4   10               2044                   34  True

Both searches answer NO at k=OPT−1k = \text{OPT} - 1 and YES at k=OPTk = \text{OPT}; the node counts are summed over the two calls.

Step 4: The full solver

Now combine: at every node, apply the reduction rules of Step 2 with the current kk, then branch as in Step 3. The solver returns the cover itself, so the result can be checked edge by edge, and it finds the minimum by trying k=0,1,2,…k = 0, 1, 2, \ldots.

python · try it yourself
import random
from itertools import combinations

def gnp(n, p, seed):
    rng = random.Random(seed)
    adj = {v: set() for v in range(n)}
    for a, b in combinations(range(n), 2):
        if rng.random() < p:
            adj[a].add(b); adj[b].add(a)
    return adj

def take(adj, v):
    for u in adj.pop(v):
        adj[u].discard(v)

def reduce(adj, k):
    adj = {v: set(nb) for v, nb in adj.items()}
    forced, changed = [], True
    while changed and k >= 0:
        changed = False
        for v in sorted(adj):
            if v not in adj:
                continue
            d = len(adj[v])
            if d == 0:
                del adj[v]; changed = True
            elif d == 1 or d > k:
                w = next(iter(adj[v])) if d == 1 else v
                take(adj, w); forced.append(w); k -= 1; changed = True
            else:
                closed = adj[v] | {v}
                if any(adj[u] | {u} <= closed for u in adj[v]):
                    take(adj, v); forced.append(v); k -= 1; changed = True
    if k < 0 or sum(map(len, adj.values())) // 2 > k * k:
        return None, k, forced
    return adj, k, forced

def paths_and_cycles(adj):
    seen, cover = set(), []
    for s in sorted(adj):
        if s in seen or not adj[s]:
            continue
        comp, stack = [], [s]
        seen.add(s)
        while stack:
            x = stack.pop(); comp.append(x)
            for y in adj[x]:
                if y not in seen:
                    seen.add(y); stack.append(y)
        start = next((x for x in comp if len(adj[x]) == 1), comp[0])
        order, prev = [start], None            # walk the path or cycle
        while True:
            nxt = [y for y in adj[order[-1]] if y != prev and y not in order]
            if not nxt:
                break
            prev = order[-1]; order.append(nxt[0])
        cover += order[1::2] if len(adj[start]) == 1 else order[0::2]
    return cover

def solve(adj, k, st):
    st[0] += 1
    adj, k, forced = reduce(adj, k)
    if adj is None:
        return None
    v = max(adj, key=lambda x: (len(adj[x]), -x), default=None)
    if v is None or not adj[v]:
        return forced
    if k <= 0:
        return None
    if len(adj[v]) <= 2:
        c = paths_and_cycles(adj)
        return forced + c if len(c) <= k else None
    for S, cost in (({v}, 1), (adj[v] | {v}, len(adj[v]))):
        rest = solve({u: nb - S for u, nb in adj.items() if u not in S}, k - cost, st)
        if rest is not None:
            return forced + ([v] if cost == 1 else sorted(adj[v])) + rest
    return None

def minimum_cover(adj):
    k, st = 0, [0]
    while True:
        C = solve(adj, k, st)
        if C is not None:
            return C, st[0]
        k += 1

def plain(adj, k, st):
    st[0] += 1
    e = next(((u, v) for u in adj for v in adj[u]), None)
    if e is None:
        return True
    if k <= 0:
        return False
    return any(plain({u: nb - {w} for u, nb in adj.items() if u != w}, k - 1, st) for w in e)

def brute(adj):
    E = [(a, b) for a in adj for b in adj[a] if a < b]
    for s in range(len(adj) + 1):
        for S in combinations(adj, s):
            if all(a in S or b in S for a, b in E):
                return s

print(" n   p    OPT  solver  valid  solver nodes  plain nodes")
for n, p, seed in [(16, 0.2, 1), (16, 0.3, 2), (18, 0.2, 3), (18, 0.25, 4), (20, 0.15, 5)]:
    G = gnp(n, p, seed)
    C, nodes = minimum_cover(G)
    valid = all(a in C or b in C for a in G for b in G[a])
    k, pst = 0, [0]
    while not plain(G, k, pst):
        k += 1
    print(f"{n:2} {p:4} {brute(G):5} {len(C):7}  {valid!s:5} {nodes:13} {pst[0]:12}")
 n   p    OPT  solver  valid  solver nodes  plain nodes
16  0.2     8       8  True              9          615
16  0.3    10      10  True             16         2253
18  0.2     9       9  True             10         2010
18 0.25    10      10  True             11         3057
20 0.15     9       9  True             10         1049

Every cover is valid and has the size brute force finds. The rules collapse most branches long before the budget runs out, so the full solver needs about a dozen nodes where plain edge branching needs hundreds or thousands.

Step 5: Scaling up

Brute force is out of the question for 2000 vertices. The generator of Step 2 at larger sizes (a random core of 24 to 36 vertices plus hubs with up to 80 leaves each) produces graphs where the rules strip the periphery and the branching does the real work on what is left of the core. The program finds the minimum, reports the kernel the rules produce at k=OPTk = \text{OPT}, the total number of search-tree nodes over all budgets k=0,1,…,OPTk = 0, 1, \ldots, \text{OPT}, and checks the cover.

python · try it yourself
import random

def take(adj, v):
    for u in adj.pop(v):
        adj[u].discard(v)

def reduce(adj, k):
    adj = {v: set(nb) for v, nb in adj.items()}
    forced, changed = [], True
    while changed and k >= 0:
        changed = False
        for v in sorted(adj):
            if v not in adj:
                continue
            d = len(adj[v])
            if d == 0:
                del adj[v]; changed = True
            elif d == 1 or d > k:
                w = next(iter(adj[v])) if d == 1 else v
                take(adj, w); forced.append(w); k -= 1; changed = True
            else:
                closed = adj[v] | {v}
                if any(adj[u] | {u} <= closed for u in adj[v]):
                    take(adj, v); forced.append(v); k -= 1; changed = True
    if k < 0 or sum(map(len, adj.values())) // 2 > k * k:
        return None, k, forced
    return adj, k, forced

def solve(adj, k, st):
    st[0] += 1
    adj, k, forced = reduce(adj, k)
    if adj is None:
        return None
    v = max(adj, key=lambda x: (len(adj[x]), -x), default=None)
    if v is None or not adj[v]:
        return forced
    if k <= 0:
        return None
    for S, cost in (({v}, 1), (adj[v] | {v}, len(adj[v]))):
        rest = solve({u: nb - S for u, nb in adj.items() if u not in S}, k - cost, st)
        if rest is not None:
            return forced + sorted(S - ({v} if cost > 1 else set())) + rest
    return None

def core_and_hubs(n, core, p, hubs, seed):
    """a random core G(core, p) plus hubs in the core carrying many pendant leaves"""
    rng = random.Random(seed)
    adj = {v: set() for v in range(n)}
    for a in range(core):
        for b in range(a + 1, core):
            if rng.random() < p:
                adj[a].add(b); adj[b].add(a)
    for h in rng.sample(range(core), hubs):
        for v in rng.sample(range(core, n), rng.randint(30, 80)):
            adj[h].add(v); adj[v].add(h)
    return adj

print("    n  core  edges  minimum  kernel at k = OPT  total nodes  valid")
for n, core, p, hubs in [(500, 24, 0.2, 4), (1000, 28, 0.18, 5), (2000, 32, 0.15, 6), (2000, 36, 0.15, 6)]:
    G = core_and_hubs(n, core, p, hubs, seed=n + core)
    total, kk = 0, 0
    while True:
        st = [0]
        C = solve(G, kk, st)
        total += st[0]
        if C is not None:
            break
        kk += 1
    K, _, _ = reduce(G, kk)
    valid = all(a in C or b in C for a in G for b in G[a])
    print(f"{n:5} {core:5} {sum(map(len, G.values())) // 2:6} {len(C):8} {len(K):11} vertices {total:12}  {valid}")
    n  core  edges  minimum  kernel at k = OPT  total nodes  valid
  500    24    294       15           0 vertices           16  True
 1000    28    332       19          16 vertices           31  True
 2000    32    348       20          22 vertices           52  True
 2000    36    467       23          23 vertices           57  True

The graphs have hundreds of edges, but the search trees have a few dozen nodes in total: the reduction rules leave kernels of at most a couple of dozen vertices, and on those the maximum-degree branching closes quickly. The cost of a solver like this is governed by the kernel, not by nn, which is the practical meaning of fixed-parameter tractability.

Step 6: The solver in C++

A compact C++ version with adjacency bitmasks (up to 64 vertices): the rules (isolated, degree 1, high degree, domination) run at every node, followed by maximum-degree branching. It solves 40-vertex random graphs for several densities and checks each cover.

cpp · try it yourself
#include <bit>
#include <cstdint>
#include <cstdio>
#include <vector>

int n;
std::vector<uint64_t> adj;
long nodes;

int deg(int v, uint64_t alive) { return std::popcount(adj[v] & alive); }

// returns true and fills `cover` if a cover of size <= k of the graph induced by `alive` exists
bool solve(uint64_t alive, int k, uint64_t& cover) {
    nodes++;
    uint64_t forced = 0;
    bool changed = true;
    while (changed) {
        changed = false;
        for (int v = 0; v < n && k >= 0; v++) {
            if (!(alive >> v & 1)) continue;
            int d = deg(v, alive);
            if (d == 0) { alive &= ~(1ULL << v); changed = true; continue; }
            int take = -1;
            if (d == 1) take = std::countr_zero(adj[v] & alive);
            else if (d > k) take = v;
            else {
                uint64_t closed = (adj[v] & alive) | (1ULL << v);
                for (uint64_t u = adj[v] & alive; u; u &= u - 1) {
                    int x = std::countr_zero(u);
                    if ((((adj[x] & alive) | (1ULL << x)) & ~closed) == 0) { take = v; break; }
                }
            }
            if (take >= 0) { forced |= 1ULL << take; alive &= ~(1ULL << take); k--; changed = true; }
        }
        if (k < 0) return false;
    }
    int best = -1, bd = 0, m = 0;
    for (int v = 0; v < n; v++)
        if (alive >> v & 1) { int d = deg(v, alive); m += d; if (d > bd) { bd = d; best = v; } }
    if (bd == 0) { cover |= forced; return true; }
    if (k == 0 || m / 2 > k * k) return false;
    uint64_t sub = 0;
    if (solve(alive & ~(1ULL << best), k - 1, sub)) { cover |= forced | (1ULL << best) | sub; return true; }
    uint64_t nb = adj[best] & alive;
    sub = 0;
    if (bd <= k && solve(alive & ~nb & ~(1ULL << best), k - bd, sub)) { cover |= forced | nb | sub; return true; }
    return false;
}

int main() {
    n = 40;
    unsigned s = 2026;
    auto rnd = [&](int m) { s = s * 1103515245u + 12345u; return int((s >> 8) % m); };
    for (int pct : {5, 10, 15, 20}) {
        adj.assign(n, 0);
        for (int a = 0; a < n; a++)
            for (int b = a + 1; b < n; b++)
                if (rnd(100) < pct) { adj[a] |= 1ULL << b; adj[b] |= 1ULL << a; }
        uint64_t all = (1ULL << n) - 1;
        long total = 0;
        for (int k = 0;; k++) {
            uint64_t cover = 0;
            nodes = 0;
            bool ok = solve(all, k, cover);
            total += nodes;
            if (ok) {
                bool valid = true;
                for (int a = 0; a < n; a++)
                    if (!(cover >> a & 1) && (adj[a] & ~cover)) valid = false;
                std::printf("density %2d%%: minimum cover %2d (size of returned set %d, valid %s), %ld nodes\n",
                            pct, k, std::popcount(cover), valid ? "yes" : "no", total);
                break;
            }
        }
    }
}
density  5%: minimum cover 16 (size of returned set 16, valid yes), 17 nodes
density 10%: minimum cover 22 (size of returned set 22, valid yes), 103 nodes
density 15%: minimum cover 23 (size of returned set 23, valid yes), 82 nodes
density 20%: minimum cover 28 (size of returned set 28, valid yes), 661 nodes

Ideas for extensions

  • Add the LP kernel of The Nemhauser-Trotter LP Kernel at the root and compare kernel sizes with Buss's rules.
  • Add crown detection (Crown Decompositions) as a fifth rule and measure how often it fires after the cheaper rules.
  • Use a lower bound to prune: if a greedy maximal matching in the remaining graph has more than kk edges, return NO at once.
  • Replace the outer loop over kk by branch and bound on the minimum, carrying the best cover found so far.

Test yourself

Why is the domination rule safe: if uu and vv are adjacent and N[u]⊆N[v]N[u] \subseteq N[v], put vv in the cover?

  1. Because vv has larger degree
  2. Because a cover without vv contains all of N(v)N(v), including uu, and swapping uu for vv keeps it a cover of the same size
  3. Because uu is isolated
  4. Because N[u]N[u] is a clique

Why does the solver try k=0,1,2,…k = 0, 1, 2, \ldots instead of starting with a large kk?

  1. Because the rules need kk to be small
  2. To find the minimum: the first kk with a YES answer is the optimum, and the cost of the earlier NO calls forms a geometric series
  3. Because large kk is incorrect
  4. To avoid recursion

What does the edge test after the reduction rules check?

  1. Whether the graph is bipartite
  2. Whether more than k2k^2 edges remain, which rules out a cover of size kk once every degree is at most kk
  3. Whether the graph is connected
  4. Whether kk is negative