"""Optimal contiguous query batches with a bounded span, versus exhaustive partitions."""
from collections import deque
from itertools import combinations_with_replacement
import json


def optimal(points,a,b,cap):
    dp=[0]
    queue=deque()
    for j,x in enumerate(points):
        value=dp[j]-b*x
        while queue and queue[-1][1]>=value:queue.pop()
        queue.append((j,value))
        while x-points[queue[0][0]]>cap:queue.popleft()
        dp.append(a+b*x+queue[0][1])
    return dp[-1]


def exhaustive(points,a,b,cap):
    best=len(points)*a
    for cut in range(1<<(len(points)-1)):
        starts=[0]+[i for i in range(1,len(points)) if cut & (1<<(i-1))]
        ends=starts[1:]+[len(points)]
        spans=[points[j-1]-points[i] for i,j in zip(starts,ends)]
        if max(spans)<=cap:
            best=min(best,a*len(spans)+b*sum(spans))
    return best


def experiment():
    checks=0
    for xs in combinations_with_replacement(range(5),5):
        for a,b,cap in ((2,1,3),(3,0,1),(1,2,0),(5,2,4)):
            assert optimal(xs,a,b,cap)==exhaustive(xs,a,b,cap)
            checks+=1
    return dict(cases=checks,example_cost=optimal([0,1,2,8,9],3,1,4))


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