"""Exact polynomial-time dynamic program for ESI Set on closed interval graphs.
Input: a list of pairs (left,right), with left<=right. Output: maximum cardinality.
Question 1 of Bozovic et al., arXiv:2611.28073.
"""
from itertools import combinations_with_replacement, product
from random import Random


def interval_esi(intervals):
    if any(l>r for l,r in intervals): raise ValueError('empty interval')
    coords = {x:i for i,x in enumerate(sorted({a for uv in intervals for a in uv}))}
    ordered = sorted((coords[l],coords[r]) for l,r in intervals)
    n=len(ordered)
    states={(-1,-1,b,w):0 for b,w in product(range(n+1),repeat=2) if b!=w or b==n}
    for i,(left,right) in enumerate(ordered):
        nxt={}
        def keep(state,value):
            if value>nxt.get(state,-1): nxt[state]=value
        for (pb,pw,fb,fw),score in states.items():
            if fb==i:
                for b in range(i+1,n+1):
                    if b==fw and b<n:continue
                    sees_b=pb>=left or (b<n and ordered[b][0]<=right)
                    sees_w=pw>=left or (fw<n and ordered[fw][0]<=right)
                    if not (sees_b or sees_w):keep((max(pb,right),pw,b,fw),score+1)
            elif fw==i:
                if pb>=left or (fb<n and ordered[fb][0]<=right):continue
                for w in range(i+1,n+1):
                    if w!=fb or w==n:keep((pb,max(pw,right),fb,w),score)
            else:
                sees_b=pb>=left or (fb<n and ordered[fb][0]<=right)
                sees_w=pw>=left or (fw<n and ordered[fw][0]<=right)
                if sees_b and sees_w:keep((pb,pw,fb,fw),score)
        states=nxt
    return max(states.values())


def exhaustive(intervals):
    n=len(intervals);adj=[0]*n;universe=(1<<n)-1
    for i,(a,b) in enumerate(intervals):
        for j,(c,d) in enumerate(intervals):
            if i!=j and max(a,c)<=min(b,d):adj[i]|=1<<j
    best=0
    for b in range(1<<n):
        if b.bit_count()<=best:continue
        neighbors=0
        for i in range(n):
            if b>>i&1:neighbors|=adj[i]
        if b&neighbors: continue
        external=universe&~(b|neighbors)
        if all(adj[i]&external for i in range(n) if neighbors>>i&1):best=b.bit_count()
    return best


if __name__=='__main__':
    models=list(combinations_with_replacement(range(4),2));count=0
    for n in range(6):
        for fam in combinations_with_replacement(models,n):
            assert interval_esi(fam)==exhaustive(fam)
            count+=1
    print('Exhaustive interval multisets checked:',count)
    rng=Random(197)
    for n in range(6,11):
        for _ in range(35):
            fam=[tuple(sorted((rng.randrange(-4,10),rng.randrange(-4,10)))) for _ in range(n)]
            assert interval_esi(fam)==exhaustive(fam)
    print('Additional seeded instances checked:',175)
