Explanation
First, given some set of cakes , it is always optimal to arrange them in sorted order by color. To prove this, consider inductively adding the cakes in ascending order. It can be shown that placing the cake between the greatest one added so far and the smallest one is always optimal. Thus, the total color is .
Sort the cakes by color. For any set of cakes, the smallest is the leftmost one and the largest is the rightmost one. The task now becomes choosing some range that maximizes the sum of the largest beauty values, minus .
Let be the optimal right endpoint for some left endpoint. We can observe that is a non-decreasing function (the proof of this has been left as an exercise to the reader). This motivates a divide and conquer solution.
Suppose we know that for . If , then we are done. Otherwise, let , and compute . We now know that lies in the range for , and in the range for . We can then recurse. By the master theorem, this will run in time.
The only step left is to compute the sum of the largest values in a range. This can be done with a variety of data structures in logarithmic time.
Time Complexity:
Implementation
C++
#include <bits/stdc++.h>using namespace std;namespace std {template <class Fun> class y_combinator_result {Fun fun_;public:template <class 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!