Table of Contents

ExplanationImplementation

Explanation

Let us define a function f(a,b)f(a,b) which denotes the cost when we place sawmills at aa and bb, a<ba < b. Let TT be the cost of transporting all trees to the base of the hill (i.e. cost without building any sawmills). Denote two arrays WW and DD that represent the prefix sum of the weight and distance, respectively.

f(a,b)=TW[a](D[b]D[a])W[b](D[n+1]D[b])f(a, b) = T - W[a] \cdot (D[b] - D[a]) - W[b] \cdot (D[n + 1] - D[b])

If we hold bb as constant, we can rearrange the equation into:

f(a,b)=TW[a]D[b]+W[a]D[a]W[b]D[n+1]+W[b]D[b]f(a, b) = T - W[a] \cdot D[b] + W[a] \cdot D[a] - W[b] \cdot D[n + 1] + W[b] \cdot D[b]
f(a,b)={(T+W[a]D[a])W[a]D[b]}W[b]D[n+1]+W[b]D[b]f(a, b) = \{(T + W[a] \cdot D[a]) - W[a] \cdot D[b]\} - W[b] \cdot D[n +1] + W[b] \cdot D[b]

Thus, ff can be decomposed into four parts: ya=T+W[a]D[a]y_a = T + W[a] \cdot D[a], ma=W[a]m_a = -W[a], x=D[b]x = D[b], c=W[b]D[n+1]+W[b]D[b]c = -W[b] \cdot D[n + 1] + W[b] \cdot D[b]. Thus,

f(a,b)=(ya+max)+cf(a, b) = (y_a + m_ax) + c

Define another function g(b)g(b) that denotes the minimum cost if we place the second sawmill at bb. This can simply be expressed in terms of f(a,b)f(a,b).

g(b)=min1a<b(ya+max)+cg(b) = \min_{1 \leq a < b} (y_a + m_a x) + c

Because xx and cc are functions of bb, we can hold them constant. Note that ya+maxy_a + m_a x forms a linear function of xx. We can use the convex hull trick to efficiently query the minimum value of a group of linear functions. The answer is simply max2bNg(b)\max_{2 \leq b \leq N}g(b).

The last thing that remains is to efficiently calculate TT.

T=w1(d1+d2++dn)+w2(d2+d3++dn)++wn(dn)T = w_1(d_1 + d_2 + \dots + d_n) + w_2(d_2 + d_3 + \dots + d_n) + \dots + w_n(d_n)
T=1knW[k]dkT = \sum_{1 \leq k \leq n} W[k] \cdot d_k

Time Complexity: O(n)\mathcal{O}(n) or O(nlogn)\mathcal{O}(n \log n) depending on the implementation of CHT. Because the following solution uses LineContainer, it runs in O(nlogn)\mathcal{O}(n \log n).

Implementation

C++

#include <bits/stdc++.h>
using namespace std;
Code Snippet: Line Container (Click to expand)
const int MAXN = 20000;
int N;
long long W[MAXN + 1], D[MAXN + 1], T;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!