You may notice that in brackets something like the equation of the line — K·X + B. That’s very similar to the equation of the line:a[l]·(x - y) + a[l]·l - sum[l], where K = a[l], X = (x - y), B = a[l]·l - sum[l].
Now we must find minimum for all l and fixed X = (x - y).
We have n lines, i. e. for every element in array a one line (K__i, B__i).
For fast answer calculation we must use Convex Hull Trick with segment tree. In every vertex of segment tree we keep all lines for segment of this vertex. This requiresspace, because each line lies invertices. And we can answer query inoperations. Because we visitvertices and each vertex need inoperations. You can learn the theory about Convex
关于斜率优化(convex hull trick)的进一步讲解
Remainder: convex hull trick lets us maintain k linear functions of the form f__i(x) = a__ix + b__i and answer efficiently (in time proportional to number of functions) to the queries Q(x) = _min_1 ≤ i ≤ kf__i(x) (given x).
Now we will be able to solve the problem if we can answer a bit more general kind of queries: we consider only lines with indices from given L and R; formally, Q(x, L, R) = min__L ≤ i ≤ Rf__i(x).
How can we do it? Let’s make a segment tree! Let’s say we have such m that 2_m_ ≥ n. Then the root contains the convex hull of lines having indices [0, 2_m_ - 1], its left child contains [0, 2_m_ - 1 - 1], right child [2_m_ - 1, 2_m_ - 1]and so on. We can costruct all these hulls one by one; without any optimizations it gives us time.
Now let’s say we have to answer the query Q(x, L, R). Then we just “break” the interval [L, R] into base intervals (in the same way a segment tree does) and for each ofsuch base intervals we find its minimum at x. Now we see that the answer is the smallest of these minima. It doesn’t matter that we consider some groups of lines from interval [L, R] separately — still, we can just take the smallest of the results.
What’s the time? We havebase intervals, for each of them we can compute the answer in, so total time is. There are some ways which let us compute all answers off-line in, but it’s not the subject :P