"""r(n) = max over w in S_n of the number of rook placements on Grid(w)
(Lewis-Won, arXiv:2609.03081, Question 3.13 / Conjecture 3.14).

Grid(w): n x n, black squares at (i, w(i)). A rook placement is a set of white squares
meeting every across word and every down word (maximal white runs) exactly once.

count(w): row-by-row transfer DP. State bit c = "the current down word of column c
already holds its rook". At row i the black square in column c = w(i) ends the north
word of column c (it must be covered if nonempty) and starts its south word.
Then one rook goes in the west word (columns < c) and one in the east word (columns > c).
Checked against an independent matching count, for all w with n <= 7.

Run: python -X utf8 lw_rn.py NMAX
"""
import sys, time, itertools
from math import factorial
import numpy as np
from numba import njit
from multiprocessing import Pool


@njit(cache=True)
def count(w, n):
    if n == 1:
        return 1  # no words: the empty placement
    size = 1 << n
    cur = np.zeros(size, np.int64)
    nxt = np.zeros(size, np.int64)
    cur[0] = 1
    for i in range(n):
        c = w[i]
        cb = 1 << c
        for s in range(size):
            nxt[s] = 0
        for s in range(size):
            v = cur[s]
            if v == 0:
                continue
            if i > 0 and (s & cb) == 0:
                continue  # north word of column c (rows 0..i-1) got no rook
            s0 = s & ~cb
            if c > 0 and c < n - 1:
                for a in range(c):
                    if s0 & (1 << a):
                        continue
                    sa = s0 | (1 << a)
                    for b in range(c + 1, n):
                        if sa & (1 << b):
                            continue
                        nxt[sa | (1 << b)] += v
            elif c == 0:
                for b in range(1, n):
                    if s0 & (1 << b) == 0:
                        nxt[s0 | (1 << b)] += v
            else:
                for a in range(n - 1):
                    if s0 & (1 << a) == 0:
                        nxt[s0 | (1 << a)] += v
        cur, nxt = nxt, cur
    full = (size - 1) & ~(1 << w[n - 1])
    return cur[full]


@njit(cache=True)
def next_perm(a, lo, n):
    # next lexicographic permutation of a[lo:n]; False when wrapped
    i = n - 2
    while i >= lo and a[i] >= a[i + 1]:
        i -= 1
    if i < lo:
        return False
    j = n - 1
    while a[j] <= a[i]:
        j -= 1
    a[i], a[j] = a[j], a[i]
    l, r = i + 1, n - 1
    while l < r:
        a[l], a[r] = a[r], a[l]
        l += 1
        r -= 1
    return True


@njit(cache=True)
def scan(prefix, n, keep):
    """All w starting with prefix: returns (best, second, maximizers[:keep], nmax)."""
    used = np.zeros(n, np.bool_)
    a = np.empty(n, np.int64)
    k = len(prefix)
    for t in range(k):
        a[t] = prefix[t]
        used[prefix[t]] = True
    p = k
    for v in range(n):
        if not used[v]:
            a[p] = v
            p += 1
    best = -1
    second = -1
    out = np.zeros((keep, n), np.int64)
    out2 = np.zeros((keep, n), np.int64)
    nmax = 0
    n2 = 0
    while True:
        x = count(a, n)
        if x > best:
            second = best
            out2[:, :] = out
            n2 = nmax
            best = x
            nmax = 0
        if x == best:
            if nmax < keep:
                out[nmax, :] = a
            nmax += 1
        elif x > second:
            second = x
            n2 = 0
        if x == second:
            if n2 < keep:
                out2[n2, :] = a
            n2 += 1
        if not next_perm(a, k, n):
            break
    return best, second, out, nmax, out2, n2


def brute(w):
    """Independent check: perfect matchings between across and down words."""
    n = len(w)
    black = {(i, w[i]) for i in range(n)}
    across, down = {}, {}
    for i in range(n):
        for j in range(n):
            if (i, j) in black:
                continue
            across[(i, j)] = (i, 0 if j < w[i] else 1)
            r = [r for r in range(n) if w[r] == j][0]
            down[(i, j)] = (j, 0 if i < r else 1)
    words = sorted(set(across.values()))
    cells = {}
    for sq, aw in across.items():
        cells.setdefault(aw, []).append(down[sq])

    def rec(k, usedd):
        if k == len(words):
            return 1
        return sum(rec(k + 1, usedd | {d}) for d in cells[words[k]] if d not in usedd)
    tot = rec(0, frozenset())
    ndown = len(set(down.values()))
    assert ndown == len(words) == 2 * n - 2 or n == 1
    return tot


def layered(n, m):  # shape (m,1,...,1,m): increasing sequence of decreasing blocks
    blocks = [m] + [1] * (n - 2 * m) + [m]
    w, base = [], 0
    for b in blocks:
        w += list(range(base + b - 1, base - 1, -1))
        base += b
    return w


def stirling2(a, b):
    S = [[0] * (b + 1) for _ in range(a + 1)]
    S[0][0] = 1
    for i in range(1, a + 1):
        for j in range(1, b + 1):
            S[i][j] = j * S[i - 1][j] + S[i - 1][j - 1]
    return S[a][b]


def prop315(n, m):
    return sum((stirling2(m, k) * k ** (n - 2 * m) * factorial(k)) ** 2 for k in range(1, m + 1))


def job(args):
    prefix, n = args
    return scan(np.array(prefix, np.int64), n, 64)


if __name__ == "__main__":
    NMAX = int(sys.argv[1]) if len(sys.argv) > 1 else 10
    # 1. DP vs independent matching count, all w, n <= 7
    for n in range(1, 8):
        for w in itertools.permutations(range(n)):
            assert count(np.array(w, np.int64), n) == brute(w), w
    print("DP = independent matching count for all w in S_n, n <= 7")
    # 2. Proposition 3.15 for layered (m,1,...,1,m)
    for n in range(2, 13):
        for m in range(2, n // 2 + 1):
            assert count(np.array(layered(n, m), np.int64), n) == prop315(n, m), (n, m)
    print("DP = Lewis-Won Prop. 3.15 for every layered (m,1,...,1,m), n <= 12")
    # 3. r(n)
    NMIN = int(sys.argv[2]) if len(sys.argv) > 2 else 1
    for n in range(NMIN, NMAX + 1):
        t0 = time.time()
        if n <= 3:
            vals = [(count(np.array(w, np.int64), n), w) for w in itertools.permutations(range(n))]
            best = max(v for v, _ in vals)
            maxi = [list(w) for v, w in vals if v == best]
            others = [v for v, _ in vals if v < best]
            second = max(others) if others else None
        else:
            prefixes = [(a, b) for a in range(n) for b in range(n) if a != b]
            with Pool(min(28, len(prefixes))) as pool:
                res = pool.map(job, [(p, n) for p in prefixes])
            best = max(r[0] for r in res)
            second = max([r[1] for r in res] + [r[0] for r in res if r[0] < best])
            maxi = [list(r[2][i]) for r in res if r[0] == best for i in range(min(r[3], 64))]
            sec = [list(r[2][i]) for r in res if r[0] == second for i in range(min(r[3], 64))] +                 [list(r[4][i]) for r in res if r[0] == best and r[1] == second for i in range(min(r[5], 64))]
            print("    runner-up perms (1-based):", [[int(x) + 1 for x in w] for w in sec[:8]], "count", len(sec))
        lay = {m: prop315(n, m) for m in range(2, n // 2 + 1)}
        lay_best = max(lay.values()) if lay else None
        lay_maxi = [layered(n, m) for m, v in lay.items() if v == best]
        print(f"n={n:2d} r(n)={best}  second={second}  #maximizers={len(maxi)}  "
              f"best layered (m,1..1,m)={lay_best} at m={[m for m, v in lay.items() if v == lay_best]}  "
              f"[{time.time() - t0:.1f}s]")
        print("    maximizers (1-based):", [[int(x) + 1 for x in w] for w in maxi[:8]])
        print("    layered maximizer among them:", any(list(w) in [list(map(int, x)) for x in maxi] for w in lay_maxi))
        sys.stdout.flush()
