Well the problem is quite easy to solve naively in O(n3) time. The problem is something like:
There are N unique points on a number line. You want to cover every
single point on the number line with some set of intervals. You can
place an interval anywhere, and it costsB + MXto create an
interval, whereBis the initial cost of creating an interval, and
Xis half the length of the interval, andMis the cost per
length of interval. You want to find the minimum cost to cover every
single interval.
Sample data:
Points = {0, 7, 100}
B = 20
M = 5
So the optimal solution would be 57.50 because you can build an interval [0,7] at cost 20 + 3.5×5 and build an interval at [100,100] at cost 100 + 0×5, which adds up to 57.50.
I have an O(n3) solution, where the DP is minimum cost to cover points from [left, right]. So the answer would be in DP[1][N]. For every pair (i,j) I just iterate over k = {i...j-1} and compute DP[i][k] + DP[k + 1][j].
However, this solution is O(n3) (kind of like matrix multiplication I think) so it’s too slow on N > 2000. Any way to optimize this?
Here’s a quadratic solution:
Sort all the points by coordinate. Call the points
p.We’ll keep an array
Asuch thatA[k]is the minimum cost to cover the firstkpoints. SetA[0]to zero and all other elements to infinity.For each
kfrom0ton-1and for eachlfromk+1ton, setA[l] = min(A[l], A[k] + B + M*(p[l-1] - p[k])/2);You should be able to convince yourself that, at the end,
A[n]is the minimum cost to cover allnpoints. (We considered all possible minimal covering intervals and we did so from “left to right” in a certain sense.)You can speed this up so that it runs in O(n log n) time; replace step 3 with the following:
Set
A[1] = B. For eachkfrom2ton, setA[k] = A[k-1] + min(M/2 * (p[k-1] - p[k-2]), B).The idea here is that we either extend the previous interval to cover the next point or we end the previous interval at
p[k-2]and begin a new one atp[k-1]. And the only thing we need to know to make that decision is the distance between the two points.Notice also that, when computing
A[k], I only needed the value ofA[k-1]. In particular, you don’t need to store the whole arrayA; only its most recent element.