Submission #762890

#TimeUsernameProblemLanguageResultExecution timeMemory
762890Oz121Knapsack (NOI18_knapsack)Java
100 / 100
991 ms141704 KiB
import java.io.*;
import java.util.*;
public class knapsack {
    public static void main(String[] args) throws IOException {
        BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer l1 = new StringTokenizer(scan.readLine());
        int W = Integer.parseInt(l1.nextToken()); int num = Integer.parseInt(l1.nextToken());

        int[][] arr = new int[num][3];
        for (int i = 0;i<num;i++) {
            StringTokenizer st = new StringTokenizer(scan.readLine());
            arr[i][0] = Integer.parseInt(st.nextToken());
            arr[i][1] = Integer.parseInt(st.nextToken());
            arr[i][2] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(arr,(a,b)->a[1]==b[1] ? b[0]-a[0] : a[1]-b[1]);

        ArrayList<Pair> weights = new ArrayList<>();

        int idx = 0;
        for (int i = 1;i<W+1;i++) {
            int count = 0;
            int max = (int) Math.floor((double) W / i);

            while (idx<num&&arr[idx][1]==i) {
                if (count < max) {
                    for (int j = 0; j < arr[idx][2] && count < max; j++) {
                        weights.add(new Pair(arr[idx][1], arr[idx][0]));
                        count++;
                    }
                }
                idx++;
            }
        }

        int size = weights.size();
        int[][] dp = new int[size][W+1];
        dp[0][weights.get(0).weight] = weights.get(0).val;

        for (int i = 1;i<size;i++) {
            for (int j = 0;j<=W;j++) {
                dp[i][j] = dp[i-1][j];

                int temp = j-weights.get(i).weight;
                if (temp>=0) {
                    dp[i][j] = Math.max(dp[i][j],dp[i-1][temp]+weights.get(i).val);
                }
            }
        }

        int ans = -1;
        for (int j = 0;j<=W;j++) {
            ans = Math.max(ans,dp[size-1][j]);
        }
        System.out.println(ans);
    }

    public static class Pair {
        int weight; int val;

        Pair (int weight, int val){
            this.weight = weight;
            this.val = val;
        }

        @Override
        public String toString() {
            return weight+" "+val;
        }
    }
}
#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...