"""Faster exhaustive r(n) for Lewis-Won Question 3.13 / Conjecture 3.14 (same DP as lw_rn.py).

Speed-ups:
 1. symmetry: the count is invariant under the 8 symmetries of the square, so only the
    lexicographically least permutation of each orbit is counted;
 2. prefix cache: dp[r] (state after rows 0..r-1) is kept and recomputed only from the
    first row that changed since the last counted permutation;
 3. last row in closed form: the count is sum over a < c < b of D[full minus {a, b}],
    with c = w(n-1) and D the state after row n-2 (one sum if c is 0 or n-1).
Checked against lw_rn.count (all w, n <= 8; random w, n = 12, 13) and against the
lw_rn.py results for n <= 12.
Run: python -X utf8 lw_rn_fast.py NMIN NMAX
"""
import sys, time, itertools, ctypes
import numpy as np
from numba import njit
from multiprocessing import Pool
from lw_rn import count, layered, prop315


@njit(cache=True)
def step(cur, nxt, c, i, n):
    size = 1 << n
    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
        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) == 0:
                        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


@njit(cache=True)
def last(D, c, n):
    full = (1 << n) - 1
    t = 0
    if c > 0 and c < n - 1:
        for a in range(c):
            for b in range(c + 1, n):
                t += D[full ^ (1 << a) ^ (1 << b)]
    elif c == 0:
        for b in range(1, n):
            t += D[full ^ (1 << b)]
    else:
        for a in range(n - 1):
            t += D[full ^ (1 << a)]
    return t


@njit(cache=True)
def count_fast(w, n):
    if n == 1:
        return 1
    size = 1 << n
    cur = np.zeros(size, np.int64)
    nxt = np.zeros(size, np.int64)
    cur[0] = 1
    for i in range(n - 1):
        step(cur, nxt, w[i], i, n)
        cur, nxt = nxt, cur
    return last(cur, w[n - 1], n)


@njit(cache=True)
def canonical(a, n, img, inv):
    for i in range(n):
        inv[a[i]] = i
    for t in range(2):
        for r in range(2):
            for c in range(2):
                if t == 0 and r == 0 and c == 0:
                    continue
                for i in range(n):
                    src = n - 1 - i if r else i
                    v = inv[src] if t else a[src]
                    img[i] = n - 1 - v if c else v
                for i in range(n):  # lexicographic compare img vs a
                    if img[i] != a[i]:
                        if img[i] < a[i]:
                            return False
                        break
    return True


@njit(cache=True)
def orbit_size(a, n, img, inv):
    # number of distinct images (for reporting)
    seen = np.zeros((8, n), np.int64)
    k = 0
    for i in range(n):
        inv[a[i]] = i
    for t in range(2):
        for r in range(2):
            for c in range(2):
                for i in range(n):
                    src = n - 1 - i if r else i
                    v = inv[src] if t else a[src]
                    img[i] = n - 1 - v if c else v
                new = True
                for q in range(k):
                    same = True
                    for i in range(n):
                        if seen[q, i] != img[i]:
                            same = False
                            break
                    if same:
                        new = False
                        break
                if new:
                    seen[k, :] = img
                    k += 1
    return k


@njit(cache=True)
def next_perm(a, lo, n):
    i = n - 2
    while i >= lo and a[i] >= a[i + 1]:
        i -= 1
    if i < lo:
        return -1
    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 i


@njit(cache=True)
def scan(prefix, n, keep):
    size = 1 << n
    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
    dp = np.zeros((n, size), np.int64)
    dp[0, 0] = 1
    img = np.empty(n, np.int64)
    inv = np.empty(n, np.int64)
    best, second = -1, -1
    out = np.zeros((keep, n), np.int64)
    out2 = np.zeros((keep, n), np.int64)
    nmax, n2, counted = 0, 0, 0
    dirty = 0
    while True:
        if canonical(a, n, img, inv):
            for r in range(dirty, n - 1):
                step(dp[r], dp[r + 1], a[r], r, n)
            dirty = n - 1
            x = last(dp[n - 1], a[n - 1], n)
            counted += 1
            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
        i = next_perm(a, k, n)
        if i < 0:
            break
        if i < dirty:
            dirty = i
    return best, second, out, nmax, out2, n2, counted


def low_priority():
    try:
        k = ctypes.windll.kernel32
        k.SetPriorityClass(k.GetCurrentProcess(), 0x4000)  # BELOW_NORMAL_PRIORITY_CLASS
    except Exception:
        pass


def job(args):
    prefix, n = args
    return scan(np.array(prefix, np.int64), n, 64)


def run(n, workers=28):
    prefixes = [(a, b) for a in range(n) for b in range(n) if a != b]
    with Pool(workers, initializer=low_priority) as pool:
        res = pool.map(job, [(p, n) for p in prefixes], chunksize=1)
    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 = [r[2][i].copy() for r in res if r[0] == best for i in range(min(r[3], 64))]
    sec = [r[2][i].copy() for r in res if r[0] == second for i in range(min(r[3], 64))] + \
        [r[4][i].copy() for r in res if r[0] == best and r[1] == second for i in range(min(r[5], 64))]
    counted = sum(r[6] for r in res)
    return best, second, maxi, sec, counted


def show(ws, n):
    img, inv = np.empty(n, np.int64), np.empty(n, np.int64)
    return [([int(x) + 1 for x in w], int(orbit_size(w, n, img, inv))) for w in ws]


if __name__ == "__main__":
    low_priority()
    NMIN, NMAX = int(sys.argv[1]), int(sys.argv[2])
    rng = np.random.default_rng(1)
    for n in range(1, 9):
        for w in itertools.permutations(range(n)):
            w = np.array(w, np.int64)
            assert count_fast(w, n) == count(w, n), w
    for n in (12, 13):
        for _ in range(300):
            w = rng.permutation(n).astype(np.int64)
            assert count_fast(w, n) == count(w, n), w
    print("count_fast = lw_rn.count: all w with n <= 8, 300 random w each for n = 12, 13")
    known = {4: (5, 2), 5: (17, 13), 6: (73, 65), 7: (469, 301), 8: (3493, 2797), 9: (28549, 21665),
             10: (255569, 245413), 11: (3316625, 2862077), 12: (46301969, 39411149)}
    for n in range(NMIN, NMAX + 1):
        t0 = time.time()
        best, second, maxi, sec, counted = run(n)
        lay = {m: prop315(n, m) for m in range(2, n // 2 + 1)}
        lay_m = [m for m, v in lay.items() if v == best]
        is_lay = any(np.array_equal(np.array(layered(n, m)), w) for m in lay_m for w in maxi)
        print(f"n={n:2d} r(n)={best} second={second} orbit reps counted={counted} "
              f"best layered={max(lay.values())} at m={lay_m} layered rep is a maximizer: {is_lay} [{time.time() - t0:.1f}s]")
        print("    maximizer orbits (rep 1-based, orbit size):", show(maxi, n))
        print("    runner-up orbits (rep 1-based, orbit size):", show(sec, n))
        if n in known:
            assert (best, second) == known[n], (n, best, second)
            print("    matches lw_rn.py")
        sys.stdout.flush()
