結果
| 問題 |
No.1606 Stuffed Animals Keeper
|
| コンテスト | |
| ユーザー |
tenten
|
| 提出日時 | 2021-07-20 19:44:19 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 115 ms / 3,000 ms |
| コード長 | 2,257 bytes |
| コンパイル時間 | 2,839 ms |
| コンパイル使用メモリ | 79,404 KB |
| 実行使用メモリ | 52,536 KB |
| 最終ジャッジ日時 | 2024-07-17 13:47:21 |
| 合計ジャッジ時間 | 8,560 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 48 |
ソースコード
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner();
int n = sc.nextInt();
int zeroCount = 0;
int oneCount = 0;
ArrayList<Integer> zeros = new ArrayList<>();
ArrayList<Integer> ones = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
if (x == 2) {
if (zeroCount > 0 || oneCount > 0) {
zeros.add(zeroCount);
ones.add(oneCount);
zeroCount = 0;
oneCount = 0;
}
} else if (x == 0) {
zeroCount++;
} else {
oneCount++;
}
}
if (zeroCount > 0 || oneCount > 0) {
zeros.add(zeroCount);
ones.add(oneCount);
}
int total = 0;
int size = zeros.size();
for (int x : zeros) {
total += x;
}
int[] dp = new int[total + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0; i < size; i++) {
int sum = zeros.get(i) + ones.get(i);
int value = ones.get(i);
for (int j = total; j - sum >= 0; j--) {
if (dp[j - sum] == Integer.MAX_VALUE) {
continue;
}
dp[j] = Math.min(dp[j], dp[j - sum] + value);
}
}
if (dp[total] == Integer.MAX_VALUE) {
System.out.println(-1);
} else {
System.out.println(dp[total]);
}
}
}
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 next() throws Exception {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
tenten