結果

問題 No.1606 Stuffed Animals Keeper
ユーザー tenten
提出日時 2021-07-20 13:54:17
言語 Java
(openjdk 23)
結果
WA  
実行時間 -
コード長 2,388 bytes
コンパイル時間 2,343 ms
コンパイル使用メモリ 78,652 KB
実行使用メモリ 156,956 KB
最終ジャッジ日時 2024-07-17 13:41:58
合計ジャッジ時間 25,655 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26 WA * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.*;
import java.util.*;

public class Main {
    static ArrayList<Integer> zeros = new ArrayList<>();
    static ArrayList<Integer> ones = new ArrayList<>();
    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 zeroCount = 0;
        int oneCount = 0;
        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);
        }
        for (int i = 0; i < zeros.size(); i++) {
            dp.add(new HashMap<>());
        }
        int ans = dfw(dp.size() - 1, 0);
        if (ans < Integer.MAX_VALUE / 2) {
            System.out.println(ans / 2);
        } else {
            System.out.println(-1);
        }
    }
    
    static int dfw(int idx, int count) {
        if (idx < 0) {
            if (count == 0) {
                return 0;
            } else {
                return Integer.MAX_VALUE / 2;
            }
        }
        if (dp.get(idx).containsKey(count)) {
            return dp.get(idx).get(count);
        }
        int ans = Math.min(dfw(idx - 1, count - zeros.get(idx)) + zeros.get(idx), dfw(idx - 1, count + ones.get(idx)) + ones.get(idx));
        dp.get(idx).put(count, 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 next() throws Exception {
        if (!st.hasMoreTokens()) {
            st = new StringTokenizer(br.readLine());
        }
        return st.nextToken();
    }
}
0