Problem Author: | Hasan Saleh (MathModel) |
Prepared by: | Hasan Saleh (MathModel) |
Edited by: | Hasan Saleh (MathModel) |
Solution
Target array must be an AP: b_i=m\cdot i+c. We can only increase entries, so for a fixed slope , the smallest feasible shift is
Then the total cost (sum of increments) is
Let S=\frac{n(n+1)}{2} and A=\sum_i a_i. Define
Then \text{cost}(m)=F(m)-A. This is the pointwise maximum of lines in a convex, unimodal function on integers. Hence we can find its minimum with the standard discrete convex search (compare ) vs f(M+1)).
Precompute \texttt{ba}_i=n\cdot a_i, \texttt{w}_i=S-n\cdot i Then
Complexity \mathcal{O}(n\log)
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
S=n*(n+1)//2
ba=[n*x for x in a]
w=[S-n*(i+1) for i in range(n)]
A=sum(a)
def F(m):
z=-10**30
for i in range(n):
v=ba[i]+m*w[i]
if v>z:z=v
return z
L=-10**9
R=10**9
while L<R:
M=(L+R)//2
if F(M)<=F(M+1):R=M
else:L=M+1
assert(F(L)<=9*10**18)
print(F(L)-A)