Let us define a function f(a,b) which denotes the cost when we place sawmills at a and b, a<b. Let T be the cost of transporting all trees to the base of the hill (i.e. cost without building any sawmills). Denote two arrays W and D that represent the prefix sum of the weight and distance, respectively.
f(a,b)=T−W[a]⋅(D[b]−D[a])−W[b]⋅(D[n+1]−D[b])
If we hold b as constant, we can rearrange the equation into:
Thus, f can be decomposed into four parts: ya=T+W[a]⋅D[a], ma=−W[a], x=D[b], c=−W[b]⋅D[n+1]+W[b]⋅D[b]. Thus,
f(a,b)=(ya+max)+c
Define another function g(b) that denotes the minimum cost if we place the second sawmill at b. This can simply be expressed in terms of f(a,b).
g(b)=1≤a<bmin(ya+max)+c
Because x and c are functions of b, we can hold them constant. Note that ya+max forms a linear function of x. We can use the convex hull trick to efficiently query the minimum value of a group of linear functions. The answer is simply max2≤b≤Ng(b).
The last thing that remains is to efficiently calculate T.