Let's consider a naive solution first. If we fix the range of restaurants that we visit, then we should always visit them in order from left to right. This will cause us to lose Al+Al+1+...+ArA_l + A_{l + 1} + ... + A_r units of happiness. Then, each ticket jj should be spent at the restaurant i[l,r]i \in [l, r] with the largest value of Bi,jB_{i, j}. Naively, this approach will run in O(N2M)\mathcal{O}(N^2 M).

Luckily for us, our happiness function C(l,r)C(l, r) satisfies the Quadrangle Inequality! To see why, let's use the alternative definition of this inequality provided in the main module:

A function C(l,r)C(l, r) satisfies the Quadrangle Inequality iff, when we increment rr, decrementing ll can only grow more expensive. Formally, for all lrl \leq r, C(l1,r)C(l,r)C(l1,r+1)C(l,r+1)C(l - 1, r) - C(l, r) \leq C(l - 1, r + 1) - C(l, r + 1).

Since we're seeking to maximize C(l,r)C(l, r), we instead look to show that incrementing rr can only diminish the additional happiness we gain by decrementing ll. This is rather intuitive: since the happiness gained from each ticket is equal to the maximum of all restaurants in our range, the impact of adding a single restaurant decreases as our range grows larger and larger.

Formally, let CiC_i denote maxj[l+1,r]Bj,i\max_{j \in [l + 1, r]} B_{j,i}, the max happiness we can get from ticket ii. Then, decrementing from l+1l + 1 to ll changes our happiness by

i=1mmax(Bl,iCi,0)Al\sum_{i=1}^m \max(B_{l,i} -C_i,0) - A_l

All CiC_i can only increase when we increment rr, and thus the above expression can only decrease.

Thus, we can apply the divide-and-conquer method described in the main module to solve this problem in O(NMlogN)\mathcal{O}(NM \log N).

Implementation

Time Complexity: O(NMlogN)\mathcal{O}(NM \log N)

C++

#include <bits/stdc++.h>
using namespace std;
#define int int64_t
const int N = 5e3 + 1;
const int M = 201;
const int K = 13;
int n, m, a[N];

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!