"""Exact weighted configurations. Compare a residual-mask DP with enumeration."""
from collections import Counter
from functools import lru_cache
from itertools import product
from math import prod
import json


def compile_counter(options, bits, prune):
    full = (1 << bits) - 1
    future = [0] * (len(options) + 1)
    for i in reversed(range(len(options))):
        future[i] = future[i+1]
        for mask, weight in options[i]:
            if weight < 0 or mask < 0 or mask > full:
                raise ValueError("invalid option")
            if weight:
                future[i] |= mask

    @lru_cache(None)
    def count(i, missing):
        if i == len(options):
            return int(missing == 0)
        if prune and missing & ~future[i]:
            return 0
        return sum(w * count(i+1, missing & ~m) for m, w in options[i] if w)

    def unrank(ticket):
        if not 0 <= ticket < count(0, full):
            raise ValueError("ticket out of range")
        missing = full
        selected = []
        for i, choices in enumerate(options):
            for j, (mask, weight) in enumerate(choices):
                rest = missing & ~mask
                block = weight * count(i+1, rest)
                if ticket < block:
                    selected.append(j)
                    ticket //= weight
                    missing = rest
                    break
                ticket -= block
        return tuple(selected)

    total = count(0, full)
    return total, unrank, count.cache_info().currsize


def experiment():
    options = [[(1,2),(1,1),(2,0)],[(2,3),(0,1)],[(4,2),(6,1)]]
    weights = {}
    for word in product(*(range(len(row)) for row in options)):
        choices = [row[j] for row,j in zip(options,word)]
        mask = 0
        for m,w in choices:
            mask |= m
        weight = prod(w for m,w in choices)
        if mask == 7 and weight:
            weights[word] = weight
    total, unrank, _ = compile_counter(options, 3, True)
    assert Counter(unrank(i) for i in range(total)) == weights
    cases = []
    for bits in (4,8,12,16):
        # Each obligation can only be supplied by its own module.
        rows = [[(1 << j,1),(1 << j,2),(0,1)] for j in range(bits)]
        mass, _, states = compile_counter(rows,bits,True)
        base, _, baseline = compile_counter(rows,bits,False)
        assert mass == base == 3**bits
        cases.append(dict(bits=bits, mass=mass, states=states, baseline_states=baseline))
    # Same obligation at every stage: every still-missing bit remains possible.
    dense = [[(1,1),(0,1)]] * 16
    x = compile_counter(dense,1,True)
    y = compile_counter(dense,1,False)
    assert x[0] == y[0] and x[2] == y[2]
    return dict(small_mass=total, small_configurations=len(weights), sparse=cases,
                dense_states=x[2], dense_baseline=y[2])


if __name__ == "__main__":
    print(json.dumps(experiment(), indent=2))
