Explanation
For each book , we either buy it, spending to gain pages, or skip it and gain nothing. This is the 0/1 knapsack problem, with cost , value , and capacity , allowing a DP solution.
Let be the maximum number of pages obtainable using only the first books with a budget of at most . The base case is for all , since with no books available, no pages can be obtained regardless of budget.
The transition follows as:
- by default (skip book )
- if , we can instead buy book , giving
The final answer is .
Since only depends on row , we don't need to keep every row around: we can compress the DP into a single 1D array of size , overwriting it in place as we go. For each book , iterate from down to , updating . Going downward matters: it keeps holding last book's value (row ) when we read it, rather than a value already updated for book (which would let us buy the same book twice).
Implementation
Time Complexity:
import java.io.*;import java.util.*;public class bookShop {public static void main(String[] args) throws IOException {BufferedReader b = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer(b.readLine());int N = Integer.parseInt(st.nextToken());int X = Integer.parseInt(st.nextToken());
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!