NOI.sg - 2019 - Feast

Author: Dong Liu


Time Complexity: O(Nloga[i])\mathcal{O}(N\log{\sum a[i]}).

C++

Like a normal Aliens Trick problem, we're going to binary search on the maximum λ\lambda where the number of subarrays used is k\geq k.

Now, for a given λ\lambda, we're going to calculate the number of people in an optimal food arrangement such that we subtract λ\lambda for every person.

Let's have dp[i][j:{0,1}]\texttt{dp}[i][j:\{0,1\}] represent the maximum sum of satisfaction of an arrangement of the first ii plates, given that j=0/1j=0/1 implies whether plate ii is being used. Let cnt[i][j]\texttt{cnt}[i][j] represent the number of people used in an optimal arrangement of dp[i][j]\texttt{dp}[i][j].

For our dp\texttt{dp} transitions, we have

{dp[i][0],cnt[i][0]}=max{{dp[i1][0],cnt[i1][0]}{dp[i1][1],cnt[i1][1]}\{\texttt{dp}[i][0], \texttt{cnt}[i][0]\} = \max\begin{cases} \{\texttt{dp}[i - 1][0], \texttt{cnt}[i - 1][0]\}\\ \{\texttt{dp}[i - 1][1], \texttt{cnt}[i - 1][1]\} \end{cases}

and

{dp[i][1],cnt[i][1]}=max{{dp[i1][0]+a[i]λ,cnt[i1][0]+1}{dp[i1][1]+a[i],cnt[i1][1]}\{\texttt{dp}[i][1], \texttt{cnt}[i][1]\} = \max\begin{cases}\{\texttt{dp}[i - 1][0] + a[i] - \lambda, \texttt{cnt}[i - 1][0] + 1\}\\ \{\texttt{dp}[i - 1][1] + a[i], \texttt{cnt}[i - 1][1]\}\end{cases}

because we either begin a new subarray or we continue an existing subarray.

Since calculating dp\texttt{dp} takes O(N)\mathcal O(N) time, and we're binary searching on the range [0,a[i]][0, \sum a[i]], the time complexity is O(Nloga[i])\mathcal{O}(N\log{\sum a[i]}).

#include <bits/stdc++.h>
using namespace std;
const int N = 300000;
const long long INF = (long long)300000 * 1000000000;
const long double EPS = 1e-3;
int n, k, a[N + 1];
pair<long double, int> dp[N + 1][2];

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!