File size: 8,949 Bytes
0dd9df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""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