제출 #450495

#제출 시각아이디문제언어결과실행 시간메모리
450495SansPapyrus683Knapsack (NOI18_knapsack)Java
73 / 100
1033 ms20696 KiB
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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...