Set A0=U0=V0=0. Let Ui be the number of operations of size 1 covering position i, and let Vi be the number of operations of size X covering position i. Then
Ui+XVi=Ai
where Ui and Vi are nonnegative integers.
For fixed sequences U,V, the required number of operations is
i=1∑Nmax(0,U
This value is attainable by starting new intervals whenever a count increases and ending existing intervals whenever it decreases.
Let Fi(c) be the minimum cost for positions 1 through i when V. Put . If the previous state is and , the transition cost is
hΔi(e)=max(0,Δ
The state must also satisfy 0≤c≤⌊Ai/X⌋. Thus, Fi is an integer discrete convex function.
For an integer discrete convex function f, define its conjugate by
f∗(s)=zmax(sz−f(z)).
For 1≤j≤X+1, define
Dj(f)=f∗(−X+j
This is the smallest optimal position at slope −X+j.
We use the following properties.
- Conjugates add under infimal convolution, so the values Dj also add.
- Restricting the domain to an integer interval [0,q] changes Dj to .
Write Δ=Xq+r with 0≤r<X. Let . If , then
d1=0,dj=
If Δ<0, then
dj=q+[r≥X−
The bracket is 1 when its condition is true and 0 otherwise. These formulas follow by examining the discrete slopes of hΔ(e)−(−X+.
Let zj=Dj(F and . Then
Dj(Fi)=clamp(z
If αi=Fi∗(−X), then
αi=αi−1−
We always have D1(Fi)=0 and D. The state never adds a negative term to . Therefore, only the states must be stored. The contribution of state can be included in a position-dependent constant.
Fix one stored state j. One position transforms an input state x as
y=clamp(x+d,0,q)
and adds min(x+d,0) to α.
The effect of any contiguous segment can be represented by five integers:
y=clamp(x+a,l,r),t=min(x+p
where t is the segment's contribution to α. A single position has summary
(a,l,r,p,c)=(d,0,q,d,0).
Suppose the left summary is (a1,l1,r1, and the right summary is . Applying the left segment and then the right segment gives
The states are independent, so merging two segment tree nodes takes O(X) time.
At the root, every input state is 0. The final value of a state is clamp(a,l,r), and its contribution to α is min(p,c). Finally, output
cminFN(c)
Read all queries in advance. If a position p is ever updated, only transitions p and p+1 can change. Let S be the set of all such transition positions. Then ∣S∣.
Positions outside S never change. Initially merge each maximal contiguous segment of such positions into one summary, while every position in S remains a summary of length 1. If the compressed sequence has length K, then
K≤2∣S∣+1≤4Q+1.
Build a segment tree on this compressed sequence. An update rebuilds only the compressed leaves corresponding to transitions p and p+1.
The preprocessing time is O(X(N+Q)+QlogQ), the time per query is O(XlogQ), and the memory usage is .
Solution written by GPT5