# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
469424 | ImaginaryIQ | Knapsack (NOI18_knapsack) | Java | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
import java.util.*;
import java.io.*;
public class Main {
static int s, n;
static int [][] arr;
static int [][] dp; // dp[i][j][k] = the maximmum amount of value that we can using the first i items,
// without exceeding weight j, while picking a max of k times
public static void main(String[] args) throws Exception {
Scanner io = new Scanner(System.in);
s = io.nextInt();
n = io.nextInt();
arr = new int[n+1][3]; // v, w, count
dp = new int[n+1][s+1];
for (int i = 1; i <= n; i++) {
arr[i][0] = io.nextInt(); // value, weight, and, number of picks
arr[i][1] = io.nextInt();
arr[i][2] = io.nextInt();
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= s; j++) {
dp[i][j] = dp[i-1][j];
// go back the number of times taken
for (int k = 1; k <= arr[i][2]; k++) {
int prev = j - (arr[i][1] * k);
if (prev >= 0) {
dp[i][j] = Math.max(dp[i-1][prev] + arr[i][0] * k, dp[i][j]);
}
}
}
}
System.out.println(dp[n][s]);
io.close();
}
static class pair implements Comparable<pair>{
int p1, p2;
public pair(int p1, int p2){
this.p1 = p1;
this.p2 = p2;
}
@Override
public int compareTo(pair o) {
return Integer.compare(this.p1, o.p1);
}
}
}