Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Any valid sequence of dishes consumed must have the following structure:

  • Before the last dish, the sum of sweetness and saltiness are both within limits
  • The last dish ends up violating one or more of the restrictions

Noticing this structure makes solving the problem much easier! The original problem required you to care about the order in which you consume dishes, but if the sum of sweetness and saltiness are all within limits, then we can consume our dishes in any order.

All that's left is to model a DP state. The most trivial DP state would be dp[i][j][k]\texttt{dp}[i][j][k], which would equal whether or not we can eat ii dishes with a sweetness sum of jj and a saltiness sum of kk. However, we can drop the kk dimension, as we always want to minimize our saltiness sum.

Thus, our final DP state is dp[i][j]\texttt{dp}[i][j] equals the minimum saltiness if we eat ii dishes with a sweetness sum of jj. Then, our transitions follow the typical form of a knapsack DP, which is

dp[i][j]=min(dp[i][j],dp[i1][ja]+b)\texttt{dp}[i][j] = \min(\texttt{dp}[i][j], \texttt{dp}[i - 1][j - a] + b)

if we are considering an item with sweetness aa and saltiness bb.

With this, we iterate over all DP states, and find the last value of ii where there's a DP values Y\leq Y. Because we can eat one last item, our printed answer is min(i+1,n)\min(i + 1, n).

Implementation

Time Complexity: O(N2X)\mathcal{O}(N^2 X)

C++

#include <bits/stdc++.h>
constexpr int INF = 1e9;
int main() {
int n, x, y;
std::cin >> n >> x >> y;
// dp[i][j] = min saltiness sum, if we eat i dishes with sweetness sum j
// note that we consider a max size of n - 1, since any more is useless

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!