"""Independent algorithms. Input is only a list of column supports. matching_signing handles column degree <= 3. small_row_feasible handles row weight <= 4. four_overlap_feasible is an exact exponential cross-check for overlaps <= 4. """ from collections import defaultdict, deque from itertools import combinations def maximum_matching(adj): """Unweighted Edmonds blossom search on a simple undirected graph.""" n = len(adj) mate = [-1] * n def augment(root): parent = [-1] * n base = list(range(n)) reached = [False] * n reached[root] = True queue = deque([root]) def common_base(a, b): ancestors = set() while True: a = base[a] ancestors.add(a) if mate[a] == -1: break a = parent[mate[a]] while base[b] not in ancestors: b = parent[mate[base[b]]] return base[b] def mark_path(v, joint, child, blossom): while base[v] != joint: blossom.update((base[v], base[mate[v]])) parent[v] = child child = mate[v] v = parent[mate[v]] while queue: u = queue.popleft() for v in adj[u]: if base[u] == base[v] or mate[u] == v: continue if v == root or (mate[v] >= 0 and parent[mate[v]] >= 0): joint = common_base(u, v) blossom = set() mark_path(u, joint, v, blossom) mark_path(v, joint, u, blossom) for w in range(n): if base[w] in blossom: base[w] = joint if not reached[w]: reached[w] = True queue.append(w) elif parent[v] == -1: parent[v] = u if mate[v] < 0: w = v while w != -1: previous = parent[w] nxt = mate[previous] mate[w], mate[previous] = previous, w w = nxt return partner = mate[v] if not reached[partner]: reached[partner] = True queue.append(partner) for vertex in range(n): if mate[vertex] < 0: augment(vertex) return mate def matching_signing(columns): """Return column dictionaries of signs, or None, for degree at most three.""" if any(len(c) > 3 for c in columns): raise ValueError("Column degree exceeds three.") adj = [] free_pool = [] pairs = defaultdict(list) choices = {} def vertex(): adj.append([]) return len(adj) - 1 def edge(a, b): adj[a].append(b) adj[b].append(a) def clique(nodes): for a, b in combinations(nodes, 2): edge(a, b) for i, col in enumerate(columns): terminals = [] for pair in combinations(sorted(col), 2): p, q = vertex(), vertex() edge(p, q) pairs[pair].append(p) terminals.append(q) choices[i, pair] = (p, q) if len(col) == 3: clique([*terminals, vertex()]) elif len(col) == 2: free_pool.extend(terminals) target_sum = 0 for ports in pairs.values(): if len(ports) % 2: return None quota = len(ports) // 2 target_sum += quota for _ in range(quota): dummy = vertex() for port in ports: edge(port, dummy) if (len(free_pool) - target_sum) % 2: free_pool.append(vertex()) clique(free_pool) mate = maximum_matching(adj) if -1 in mate: return None signing = [] for i, col in enumerate(columns): rows = sorted(col) signs = {} if rows: signs[rows[0]] = 1 for r in rows[1:]: p, q = choices[i, (rows[0], r)] signs[r] = -1 if mate[p] == q else 1 signing.append(signs) return signing class XorBasis: """Affine equations encoded by bit masks, with bit 0 the constant term.""" def __init__(self, pivots=None): self.pivots = {} if pivots is None else dict(pivots) def reduce(self, form): free = 0 while form > 1: pivot = form.bit_length() - 1 if pivot in self.pivots: form ^= self.pivots[pivot] else: bit = 1 << pivot free |= bit form ^= bit return free | form def add_zero(self, form): remainder = self.reduce(form) if remainder > 1: self.pivots[remainder.bit_length() - 1] = remainder return remainder != 1 def four_overlap_feasible(columns): """Exact support-only checker via XOR equations and pairs of XOR literals.""" basis = XorBasis() clauses = [] pairs = defaultdict(list) next_bit = 1 for col in columns: rows = sorted(col) if len(rows) == 2: pairs[tuple(rows)].append(None) # freely choosable pair product elif len(rows) >= 3: # Column switches set the first entry to +1. bits = {rows[0]: 0} for r in rows[1:]: bits[r] = 1 << next_bit next_bit += 1 for a, b in combinations(rows, 2): pairs[a, b].append(bits[a] ^ bits[b]) for path_bits in pairs.values(): k = len(path_bits) if k % 2: return False if k > 4: raise ValueError("Row overlap exceeds four.") h = [a for a in path_bits if a is not None] if 2 * len(h) <= k: continue if len(h) == 2: if not basis.add_zero(h[0] ^ h[1] ^ 1): return False else: if len(h) == 4 and not basis.add_zero(h[0] ^ h[1] ^ h[2] ^ h[3]): return False clauses.append((h[0] ^ h[1], h[0] ^ h[2])) def solve(current, remaining): while True: undecided = [] progress = False for a, b in remaining: a, b = current.reduce(a), current.reduce(b) if a == 1 or b == 1 or (a ^ b) == 1: continue if a == 0 or b == 0 or a == b: literal = b if a == 0 else a if not current.add_zero(literal ^ 1): return False progress = True else: undecided.append((a, b)) if not undecided: return True remaining = undecided if not progress: break a, b = min(remaining, key=lambda pair: sum(x.bit_count() for x in pair)) left = XorBasis(current.pivots) if left.add_zero(a ^ 1) and solve(left, remaining): return True return current.add_zero(a) and current.add_zero(b ^ 1) and solve(current, remaining) return solve(basis, clauses) def small_row_feasible(columns): """Exact polynomial test for row weight <= 4, using twin classes and XOR.""" rows = defaultdict(set) forms = {} for j, col in enumerate(columns): for i in col: forms[i, j] = 1 << (len(forms) + 1) rows[i].add(j) if any(len(s) > 4 for s in rows.values()): raise ValueError("Row weight exceeds four.") basis = XorBasis() twins = defaultdict(list) for row, support in rows.items(): if len(support) == 4: twins[frozenset(support)].append(row) for r, s in combinations(rows, 2): shared = rows[r] & rows[s] if len(shared) % 2: return False if len(shared) == 2: a, b = tuple(shared) if not basis.add_zero(forms[r,a] ^ forms[s,a] ^ forms[r,b] ^ forms[s,b] ^ 1): return False for support, group in twins.items(): if len(group) < 2: continue exterior = next((v for v in rows if rows[v] != support and rows[v] & support), None) if exterior is None: if len(group) > 4: return False continue if len(group) > 2: return False r, s = group a, b = tuple(rows[exterior] & support) c, d = tuple(support - {a, b}) relative = {j: forms[r,j] ^ forms[s,j] for j in support} for form in (relative[a] ^ relative[b], relative[c] ^ relative[d], relative[a] ^ relative[c] ^ 1): if not basis.add_zero(form): return False return True