"""Exact independent checks of the prefix couplings and Chan-Pak inequalities."""

from collections import defaultdict, deque
from functools import cache


def members(mask):
    while mask:
        bit = mask & -mask
        yield bit.bit_length() - 1
        mask ^= bit


def natural_posets(size):
    pairs = [(i, j) for j in range(size) for i in range(j)]
    for relation in range(1 << len(pairs)):
        pred = [0] * size
        for bit, (i, j) in enumerate(pairs):
            if relation & (1 << bit):
                pred[j] |= 1 << i
        if all(not (pred[i] & ~p) for p in pred for i in members(p)):
            yield pred


def prefix_weights(pred):
    size = len(pred)
    full = (1 << size) - 1

    @cache
    def extensions(mask):
        if not mask:
            return 1
        return sum(extensions(mask ^ (1 << i)) for i in members(mask)
                   if not (pred[i] & mask))

    layers = [[{} for _ in range(size)] for _ in range(size)]
    for ideal in range(1 << size):
        if any(pred[i] & ~ideal for i in members(ideal)):
            continue
        outside = full ^ ideal
        for x in members(outside):
            if not (pred[x] & outside):
                layers[x][ideal.bit_count()][ideal] = (
                    extensions(ideal) * extensions(outside ^ (1 << x))
                )
    return layers


def verify_flow(lower, upper):
    """Use integral capacities for the marginals after clearing denominators."""
    left_total = sum(lower.values())
    right_total = sum(upper.values())
    target = left_total * right_total
    source = (-1, 0)
    sink = (2, 0)
    edges = defaultdict(dict)

    def connect(a, b, capacity):
        edges[a][b] = capacity
        edges[b][a] = 0

    for a, count in lower.items():
        connect(source, (0, a), count * right_total)
    for b, count in upper.items():
        connect((1, b), sink, count * left_total)
    for a in lower:
        for b in upper:
            if a & b == a:
                connect((0, a), (1, b), target)

    flow = 0
    while flow < target:
        previous = {source: None}
        pending = deque([source])
        while pending and sink not in previous:
            current = pending.popleft()
            for following, capacity in edges[current].items():
                if capacity > 0 and following not in previous:
                    previous[following] = current
                    pending.append(following)
        assert sink in previous, (lower, upper)
        path = []
        current = sink
        while current != source:
            parent = previous[current]
            path.append((parent, current))
            current = parent
        amount = min(edges[a][b] for a, b in path)
        for a, b in path:
            edges[a][b] -= amount
            edges[b][a] += amount
        flow += amount


def verify_size(size):
    tested_posets = tested_couplings = tested_inequalities = 0
    for pred in natural_posets(size):
        tested_posets += 1
        for layers in prefix_weights(pred):
            rank_counts = [0] + [sum(layer.values()) for layer in layers]
            for lower, upper in zip(layers, layers[1:]):
                if lower and upper:
                    verify_flow(lower, upper)
                    tested_couplings += 1
            for a in range(1, size):
                for b in range(a + 1, size + 1):
                    assert ((b - 1) * rank_counts[b - 1] * rank_counts[a] >=
                            (a - 1) * rank_counts[a - 1] * rank_counts[b] +
                            (b - a) * rank_counts[a] * rank_counts[b])
                    tested_inequalities += 1
    return tested_posets, tested_couplings, tested_inequalities


if __name__ == "__main__":
    print("order  naturally_labeled_posets  couplings  rank_inequalities")
    for size in range(1, 7):
        print(size, *verify_size(size), flush=True)

