結果
| 問題 |
No.527 ナップサック容量問題
|
| コンテスト | |
| ユーザー |
tenten
|
| 提出日時 | 2021-11-02 11:50:16 |
| 言語 | Java (openjdk 23) |
| 結果 |
TLE
(最新)
AC
(最初)
|
| 実行時間 | - |
| コード長 | 2,511 bytes |
| コンパイル時間 | 3,298 ms |
| コンパイル使用メモリ | 78,804 KB |
| 実行使用メモリ | 324,564 KB |
| 最終ジャッジ日時 | 2024-10-11 10:18:34 |
| 合計ジャッジ時間 | 27,180 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 35 TLE * 2 |
ソースコード
import java.io.*;
import java.util.*;
public class Main {
static int[] weights;
static int[] values;
static ArrayList<HashMap<Integer, Integer>> dp = new ArrayList<>();
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner();
int n = sc.nextInt();
int totalW = 0;;
int totalV = 0;
weights = new int[n];
values = new int[n];
for (int i = 0; i < n; i++) {
values[i] = sc.nextInt();
totalV += values[i];
weights[i] = sc.nextInt();
totalW += weights[i];
dp.add(new HashMap<>());
}
int v = sc.nextInt();
int left1 = 0;
int right1 = totalW;
while (right1 - left1 > 1) {
int m = (left1 + right1) / 2;
if (dfw(n - 1, m) >= v) {
right1 = m;
} else {
left1 = m;
}
}
if (totalV == v) {
System.out.println(right1);
System.out.println("inf");
return;
}
int left2 = right1;
int right2 = totalW;
while (right2 - left2 > 1) {
int m = (left2 + right2) / 2;
if (dfw(n - 1, m) > v) {
right2 = m;
} else {
left2 = m;
}
}
System.out.println(right1);
System.out.println(left2);
}
static int dfw(int idx, int w) {
if (w < 0) {
return Integer.MIN_VALUE;
}
if (idx < 0) {
return 0;
}
if (dp.get(idx).containsKey(w)) {
return dp.get(idx).get(w);
}
int ans = Math.max(dfw(idx - 1, w), dfw(idx - 1, w - weights[idx]) + values[idx]);
dp.get(idx).put(w, ans);
return ans;
}
}
class Scanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public Scanner() throws Exception {
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public String nextLine() throws Exception {
return br.readLine();
}
public String next() throws Exception {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
tenten