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 units of happiness. Then, each ticket should be spent at the restaurant with the largest value of . Naively, this approach will run in .
Luckily for us, our happiness function satisfies the Quadrangle Inequality! To see why, let's use the alternative definition of this inequality provided in the main module:
A function satisfies the Quadrangle Inequality iff, when we increment , decrementing can only grow more expensive. Formally, for all , .
Since we're seeking to maximize , we instead look to show that incrementing can only diminish the additional happiness we gain by decrementing . 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 denote , the max happiness we can get from ticket . Then, decrementing from to changes our happiness by
All can only increase when we increment , 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 .
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;#define int int64_tconst 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!