이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
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 (count<max&&idx<num&&arr[idx][1]==i) {
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];
if (j-weights.get(i).weight>=0) {
dp[i][j] = Math.max(dp[i][j],dp[i-1][j-weights.get(i).weight]+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 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... |