import java.util.*;
import java.io.*;
public class knapsack {
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 = 0; i < n+1; i++) {
Arrays.fill(dp[i], Integer.MIN_VALUE);
}
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();
}
dp [0][0] = 0;
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 <= Math.min(arr[i][2], n); k++) {
int prev = j - (arr[i][1] * k);
if (prev >= 0 && dp[i-1][prev] != Integer.MIN_VALUE) {
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);
}
}
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
126 ms |
10308 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
157 ms |
11136 KB |
Output is correct |
2 |
Incorrect |
191 ms |
13872 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
157 ms |
11136 KB |
Output is correct |
2 |
Incorrect |
191 ms |
13872 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
126 ms |
10308 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
126 ms |
10308 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |