# Use as follows, with the right path
# $ python db-61.py ../../Nobackup/tinv61.txt
import sys
N = 61

def analyze_model(mag):
    bag = set((i, j) for i in range(N) for j in range(N) if i != j)
    while bag:
        e0 = bag.pop()
        block_edges = set()
        candidates = {e0}
        while candidates:
            x, y = e1 = candidates.pop()
            block_edges.add(e1)
            e2 = (mag[x][y], x)
            if e2 in bag:
                candidates.add(e2)
                bag.remove(e2)
            e3 = (y, mag[mag[x][y]][x])
            if e3 in bag:
                candidates.add(e3)
                bag.remove(e3)
            e4 = (x, mag[y][mag[mag[x][y]][x]])
            if e4 in bag:
                candidates.add(e4)
                bag.remove(e4)
        block = set(v for e in block_edges for v in e)
        if (set(e for e in block_edges if e[0] != e[1])
            != set((x, y) for x in block for y in block if x != y)):
            print(block, block_edges)
            quit()
        if len(block) != 5:
            print(block)
            quit()

with open(sys.argv[1], 'r') as f:
    mag = []
    for line in f:
        if line.strip() == f"Model of size {N} found by tinv_dpll:":
            if not mag:
                continue
            if len(mag) != N:
                raise ValueError((len(mag), len(mag[0])))
            analyze_model(mag)
            mag = []
            continue
        mag.append(list(int(s) for s in line.strip().split(' ') if s != ''))

