"""Exact placement counts for the permutation-grid convention of Lewis and Won."""

from functools import cache
from itertools import permutations
from sys import argv


def word_masks(board):
    """Return one adjacency mask per nonempty across word."""
    size = len(board)
    black_row = [0] * size
    for row, col in enumerate(board):
        black_row[col] = row
    masks = []
    for row, black_col in enumerate(board):
        left = right = 0
        for col, split_row in enumerate(black_row):
            if col < black_col:
                left |= 1 << (2 * col + (row > split_row))
            if col > black_col:
                right |= 1 << (2 * col + (row > split_row))
        if left:
            masks.append(left)
        if right:
            masks.append(right)
    return tuple(sorted(masks, key=int.bit_count))


def rook_count(board):
    """Count perfect matchings by retaining the set of occupied down words."""
    masks = word_masks(board)

    @cache
    def count(used):
        row = used.bit_count()
        if row == len(masks):
            return 1
        available = masks[row] & ~used
        total = 0
        while available:
            choice = available & -available
            available -= choice
            total += count(used | choice)
        return total

    answer = count(0)
    count.cache_clear()
    return answer


def ryser_count(board):
    """Independently evaluate Ryser's inclusion-exclusion formula."""
    rows = word_masks(board)
    all_down = 0
    for row in rows:
        all_down |= row
    assert len(rows) == all_down.bit_count()
    result = 0
    subset = all_down
    while True:
        product = 1
        for row in rows:
            product *= (row & subset).bit_count()
            if product == 0:
                break
        result += -product if (len(rows) - subset.bit_count()) % 2 else product
        if not subset:
            return result
        subset = (subset - 1) & all_down


def excluded(count):
    return count in (4, 12) or count % 4 == 3


if __name__ == "__main__":
    example = tuple(x - 1 for x in (2, 7, 4, 8, 1, 6, 3, 5))
    assert rook_count(example) == ryser_count(example) == 155
    limit = int(argv[1]) if len(argv) > 1 else 8
    for size in range(1, limit + 1):
        witnesses = {}
        for board in permutations(range(size)):
            count = rook_count(board)
            if excluded(count) and count not in witnesses:
                witnesses[count] = tuple(x + 1 for x in board)
        print(f"n={size}: {sorted(witnesses.items())}", flush=True)

