"""Construction: if 1 <= |S| <= |T|, d = |T|-|S|, T has >= d+1 runs and S has >= 2d+1 runs,
then some w has D(w) = S and D(w^-1) = T.  Both sets are realised by tableaux of shape (n-|T|, d+1, 1^(|S|-1))."""
import itertools, random, sys

def runs(S):
    S = sorted(S); out = []
    for x in S:
        if out and out[-1][1] == x - 1: out[-1][1] = x
        else: out.append([x, x])
    return out

def word_big(T, n, d):
    """row word for the larger set: d+1 run-starts get letter 2, other descents go down the leg."""
    R = runs(T); X = {r[0] for r in R[:d + 1]}
    rho = [1]; leg = 3
    for i in range(1, n):
        if i in X: rho.append(2)
        elif i in T: rho.append(leg); leg += 1
        else: rho.append(1)
    return rho

def word_small(S, n, d):
    """row word for the smaller set: first descent gets letter 2, the rest go down the leg,
    and d extra 2's are placed two steps after the end of the last d runs that end before n-1."""
    R = runs(S); first = R[0][0]
    slots = [r[1] + 2 for r in R if r[1] + 2 <= n]          # position e+2
    use = set(slots[len(slots) - d:]) if d else set()
    rho = [1]; leg = 3
    for i in range(1, n):                                    # letter of position i+1
        if i == first: rho.append(2)
        elif i in S: rho.append(leg); leg += 1
        elif (i + 1) in use: rho.append(2)
        else: rho.append(1)
    return rho

def tableau(rho):
    rows = {}
    for k, r in enumerate(rho, 1): rows.setdefault(r, []).append(k)
    T = [rows[r] for r in sorted(rows)]
    assert sorted(rows) == list(range(1, len(rows) + 1))
    for a, b in zip(T, T[1:]):
        assert len(b) <= len(a) and all(b[j] > a[j] for j in range(len(b))), "not a standard tableau"
    return T

def inverse_rsk(P, Q):
    P = [r[:] for r in P]; Q = [r[:] for r in Q]; n = sum(map(len, P)); w = [0] * (n + 1)
    for k in range(n, 0, -1):
        r = next(i for i, row in enumerate(Q) if row and row[-1] == k)
        Q[r].pop(); x = P[r].pop()
        for i in range(r - 1, -1, -1):
            j = max(j for j, y in enumerate(P[i]) if y < x)
            P[i][j], x = x, P[i][j]
        w[k] = x
    return w[1:]

def D(w): return {i + 1 for i in range(len(w) - 1) if w[i] > w[i + 1]}
def inv(w):
    v = [0] * len(w)
    for i, x in enumerate(w): v[x - 1] = i + 1
    return v

def build(S, T, n):
    """returns w with D(w)=S, D(w^-1)=T, assuming |S| <= |T| and the run conditions"""
    d = len(T) - len(S)
    Q = tableau(word_small(S, n, d)); P = tableau(word_big(T, n, d))
    assert [len(r) for r in P] == [len(r) for r in Q]
    return inverse_rsk(P, Q)

def condition(S, T):
    d = len(T) - len(S)
    return len(S) >= 1 and d >= 0 and len(runs(T)) >= d + 1 and len(runs(S)) >= 2 * d + 1

if __name__ == '__main__':
    N = int(sys.argv[1])
    for n in range(2, N + 1):
        subs = [frozenset(c) for k in range(n) for c in itertools.combinations(range(1, n), k)]
        good = 0; covered = set()
        for S in subs:
            for T in subs:
                if condition(S, T):
                    w = build(S, T, n); assert D(w) == S and D(inv(w)) == T, (S, T, w)
                    good += 1; covered.add((S, T)); covered.add((T, S))
        print(n, 'pairs built and verified:', good, '| covered incl. swap + (empty,empty):', len(covered) + 1, '| 4^(n-1) =', 4 ** (n - 1))
    random.seed(5)
    for n in (30, 100, 400):
        ok = tried = 0
        for _ in range(300):
            S = {i for i in range(1, n) if random.random() < .5}; T = {i for i in range(1, n) if random.random() < .5}
            if len(S) > len(T): S, T = T, S
            tried += 1
            if condition(S, T):
                w = build(S, T, n); assert D(w) == S and D(inv(w)) == T; ok += 1
        print('random n =', n, ':', ok, 'of', tried, 'pairs satisfy the condition, all built and verified')
