이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class knapsack {
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer initial = new StringTokenizer(read.readLine());
int limit = Integer.parseInt(initial.nextToken());
int typeNum = Integer.parseInt(initial.nextToken());
HashMap<Integer, ArrayList<int[]>> byWeight = new HashMap<>();
for (int t = 0; t < typeNum; t++) {
// value, weight, and amt respectively
int[] item = Arrays.stream(read.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
if (item[1] <= limit && 0 <= item[2]) {
if (!byWeight.containsKey(item[1])) {
byWeight.put(item[1], new ArrayList<>());
}
byWeight.get(item[1]).add(new int[] {item[0], item[2]});
}
}
long[][] best = new long[byWeight.size() + 1][limit + 1];
for (long[] row : best) {
Arrays.fill(row, Integer.MIN_VALUE);
}
best[0][0] = 0;
int at = 1;
for (var pair : byWeight.entrySet()) {
int w = pair.getKey();
ArrayList<int[]> items = pair.getValue();
items.sort(Comparator.comparingInt(i -> -i[0]));
for (int i = 0; i <= limit; i++) {
best[at][i] = best[at - 1][i];
int copies = 0;
int typeAt = 0;
int curr_used = 0;
long profit = 0;
while ((copies + 1) * w <= i && typeAt < items.size()) {
copies++;
profit += items.get(typeAt)[0];
if (best[at - 1][i - copies * w] != Integer.MIN_VALUE) {
best[at][i] = Math.max(
best[at][i],
best[at - 1][i - copies * w] + profit
);
}
curr_used++;
if (curr_used == items.get(typeAt)[1]) {
curr_used = 0;
typeAt++;
}
}
}
at++;
}
System.out.println(Arrays.stream(best[byWeight.size()]).max().getAsLong());
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |