"""Breadth-first minimum materializations for two explicit acyclic proof dependency graphs."""
from collections import deque
from itertools import combinations,permutations
import json

GRAPHS={'star':[(),(0,),(0,),(0,),(1,2),(2,3),(1,3)],
        'chain':[(),(0,),(1,),(2,),(0,1),(1,2),(2,3)]}


def solve(parents,order,cap,early):
    start=(frozenset(),0);seen={start:None};queue=deque([start])
    while queue:
        state=queue.popleft();held,i=state
        if i==len(order):
            trace=[]
            while seen[state]:
                prev,line=seen[state];trace.append([line,sorted(state[0]),state[1]]);state=prev
            return list(reversed(trace))
        for line,needs in enumerate(parents):
            if line in held or line in order[:i] or not held.issuperset(needs):continue
            if not early and line in order[i+1:]:continue
            for old in combinations(sorted(held),min(cap-1,len(held))):
                live=set(old)|{line};j=i
                while j<len(order) and order[j] in live:live.remove(order[j]);j+=1
                nxt=(frozenset(live),j)
                if nxt not in seen:seen[nxt]=(state,line);queue.append(nxt)
    return None


def study():
    rows=[]
    for label,parents in GRAPHS.items():
        for i,order in enumerate(permutations((4,5,6))):
            for cap in (2,3,4):
                traces=[solve(parents,order,cap,flag) for flag in (False,True)]
                for trace in traces:
                    held=set();progress=0
                    if trace is None:continue
                    for line,keep,j in trace:
                        assert held.issuperset(parents[line]) and line not in held
                        step=set(keep)|set(order[progress:j])
                        assert step<=(held|{line}) and len(step)<=cap and line in step
                        held=set(keep);progress=j
                    assert progress==3
                costs=[len(t) if t is not None else None for t in traces]
                assert costs[0] is None or costs[1]<=costs[0]
                rows.append(dict(graph=label,order=i,sequence=order,cap=cap,strict=costs[0],early=costs[1],trace=traces[1]))
    return rows


if __name__=='__main__':print(json.dumps(study(),indent=2))
