結果
問題 |
No.1606 Stuffed Animals Keeper
|
ユーザー |
![]() |
提出日時 | 2022-08-18 14:26:25 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 180 ms / 3,000 ms |
コード長 | 2,740 bytes |
コンパイル時間 | 2,071 ms |
コンパイル使用メモリ | 78,400 KB |
実行使用メモリ | 63,032 KB |
最終ジャッジ日時 | 2024-10-06 05:07:44 |
合計ジャッジ時間 | 9,267 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 48 |
ソースコード
import java.io.*; import java.util.*; public class Main { static ArrayList<Animal> animals = new ArrayList<>(); static int[][] dp; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); int n = sc.nextInt(); int meat = 0; int grass = 0; int sumMeat = 0; for (int i = 0; i < n; i++) { int x = sc.nextInt(); if (x == 0) { meat++; } else if (x == 1) { grass++; } else { if (meat > 0 || grass > 0) { animals.add(new Animal(meat, grass)); sumMeat += meat; meat = 0; grass = 0; } } } if (meat > 0 || grass > 0) { animals.add(new Animal(meat, grass)); sumMeat += meat; } dp = new int[animals.size()][sumMeat + 1]; for (int[] arr : dp) { Arrays.fill(arr, -1); } int ans = dfw(animals.size() - 1, sumMeat); if (ans >= Integer.MAX_VALUE / 2) { System.out.println(-1); } else { System.out.println(ans / 2); } } static int dfw(int idx, int value) { if (value < 0) { return Integer.MAX_VALUE / 2; } if (idx < 0) { if (value == 0) { return 0; } else { return Integer.MAX_VALUE / 2; } } if (dp[idx][value] < 0) { dp[idx][value] = Math.min(dfw(idx - 1, value) + animals.get(idx).meat, dfw(idx - 1, value - animals.get(idx).sum()) + animals.get(idx).grass); } return dp[idx][value]; } static class Animal { int meat; int grass; public Animal(int meat, int grass) { this.meat = meat; this.grass = grass; } public int sum() { return meat + grass; } } } 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 double nextDouble() throws Exception { return Double.parseDouble(next()); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }