"""Integer certificate for 17 as the maximum on 81 real points in dimension four."""
from functools import lru_cache
from itertools import combinations, product
from math import comb

N = 81
target = 18
vertices = 16


@lru_cache(None)
def partitions(n, lower=1):
    if n == 0:
        return ((),)
    return tuple((a,)+rest for a in range(lower,n+1)
                 for rest in partitions(n-a,a))


def profiles():
    rows=[[0,1]]
    for dimension in range(1,5):
        prior=rows[-1]
        row=[0]
        for n in range(1,target+1):
            prices=[]
            for p in partitions(n):
                if p[-1] < len(prior):
                    v=[prior[i] for i in p]
                    prices.append(sum(v)+max(v))
            row.append(min(prices))
        rows.append(row)
    return rows


def check_dominance():
    # Maximum number of coordinate-axis unit adjacencies on up to six vertices.
    # Check every bipartite graph of these orders that has no K_(2,3).
    edges=[0]*(7)
    for r in range(1,7):
        for n in range(r//2+1):
            m=r-n
            for bits in range(1<<(n*m)):
                rows=[(bits>>(m*i))&((1<<m)-1) for i in range(n)]
                cols=[sum(((rows[i]>>j)&1)<<i for i in range(n)) for j in range(m)]
                if any((x&y).bit_count()>2 for a in (rows,cols)
                       for x,y in combinations(a,2)):
                    continue
                edges[r]=max(edges[r],bits.bit_count())
    assert edges == [0,0,1,2,4,5,7]
    maximum=max(comb(target,2)+sum(3*comb(t,2)+4*edges[t] for t in p)
                for p in partitions(target) if p[-1]<=6)
    assert maximum==372 < 3*(target*vertices)-6*N==378


def beta(r):
    return min(x+y for x in range(1,r+1) for y in range(1,r+1) if x*y>=r)


def parity_minimum(r,b,F):
    # A host has 8 pairs of opposite parity classes; all contain a unit vertex.
    return 8*beta(r) if b==0 else F[b]+1+7*beta(r)


def independent_parity_check(r,b,F):
    # Without merging pairs analytically, allocate each of the b side-two cubes.
    costs=[10**9]*(b+1)
    for u in range(b+1):
        for v in range(b-u+1):
            lo=max(1,F[u])
            hi=max(lo,r)
            for x in range(lo,hi+1):
                y=max(1,F[v],(r+x-1)//x)
                costs[u+v]=min(costs[u+v],x+y)
    totals=[0]+[10**9]*b
    for _ in range(8):
        totals=[min(totals[k-j]+costs[j] for j in range(k+1)) for k in range(b+1)]
    return totals[b]


def uncovered_large(t, u, F):
    # Cubes of a fixed large side can occupy several cosets of that side's lattice.
    return min(sum(max(0,F[s]-u//16) for s in p) for p in partitions(t))


def integer_case(r, F):
    # r=16 has the separate equality proof. Test all possible other scales by size.
    for b in range(min(r,target-r)+1):
        if parity_minimum(r,b,F)>N:
            continue
        for big in partitions(target-r-b):
            if big and big[-1]>r:
                continue
            for u in range(F[r],N+1):
                # Even one large cube puts sixteen separated vertices in the host.
                if big and u+16-u//16>N:continue
                # For up to three size groups use the first two inclusion-exclusion terms.
                outside=0
                for m in range(1,min(3,len(big))+1):
                    for group in combinations(big,m):
                        lower=sum(uncovered_large(t,u,F) for t in group)
                        overlap=sum(x*y for x,y in combinations(group,2))
                        outside=max(outside,lower-overlap)
                assert u+outside>N, ('surviving integral spectrum',r,b,big,u)


def nonintegral_case(r, F):
    possible=[p for p in partitions(r) if 16+sum(F[t]-1 for t in p)<=N]
    expected={7:[(1,6),(7,)],8:[(8,)],9:[(9,)],10:[(10,)]}
    assert possible==expected.get(r,[])
    for p in possible:
        if len(p)==2:
            # The nonintegral cube uses one point per coset, and at least 14 outside both.
            assert p==(1,6) and N-F[6]-F[1]<2*14-8
            assert N-F[6]-14<2*16-1
            assert N-F[1]-14-F[6]<16-((N-F[1]-14)//16)
            assert 7+1+7<target
            continue
        for rich in range(F[r],N-14):
            out=N-rich
            assert out<=29 and out-14<16
            # Four of one nonintegral side, or two of one side plus one of another,
            # or three unrelated sizes would each use more outside points than exist.
            assert min(F[4]-4,(F[2]-2)+(16-1)-2,3*15-3)>out
            # At most one integral cube of side >= 3 can fit in the rich coset.
            assert 2*(16-rich//16)-8>rich-F[r]
            assert parity_minimum(r,2,F)>rich
            assert r+3+1+1<target


def run():
    rows=profiles()
    F=rows[4]
    assert F == [0,16,24,32,36,44,48,52,54,62,66,70,72,76,78,80,81,89,93]
    assert [p for p in partitions(16) if sum(rows[3][i] for i in p)
            +max(rows[3][i] for i in p)<=N]==[(8,8)]
    assert min(F[i]+F[j]-F[i+j] for i in range(1,17)
               for j in range(1,17-i))>=8
    check_dominance()
    for r in range(7,17):
        for b in range(0,min(16,r)+1):
            assert independent_parity_check(r,b,F) >= parity_minimum(r,b,F)
        nonintegral_case(r,F)
        if r<16:
            integer_case(r,F)
    grid=set(product(range(3),repeat=4))
    counts=[]
    for h in (1,2):
        counts.append(sum(all(tuple(x+h*y for x,y in zip(a,z)) in grid
                              for z in product((0,1),repeat=4)) for a in grid))
    assert counts==[16,1]
    print('Exact arithmetic verified for all multiplicity partitions of 18.')
    print('Dominant scale: 7 through 16. All remaining 18-cube cases excluded.')
    print('The 81-point regular grid realizes 16 + 1 = 17.')


if __name__=='__main__':
    run()
