結果

問題 No.545 ママの大事な二人の子供
ユーザー tenten
提出日時 2021-03-09 08:21:17
言語 Java
(openjdk 23)
結果
AC  
実行時間 460 ms / 2,000 ms
コード長 1,702 bytes
コンパイル時間 3,347 ms
コンパイル使用メモリ 79,116 KB
実行使用メモリ 65,048 KB
最終ジャッジ日時 2024-10-10 23:11:07
合計ジャッジ時間 12,157 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n == 1) {
            System.out.println(Math.min(sc.nextLong(), sc.nextLong()));
            return;
        }
        int n1 = n / 2;
        int n2 = n - n1;
        long[][] arr1 = new long[n1][2];
        for (int i = 0; i < n1; i++) {
            arr1[i][0] = sc.nextLong();
            arr1[i][1] = -sc.nextLong();
        }
        long[][] arr2 = new long[n2][2];
        for (int i = 0; i < n2; i++) {
            arr2[i][0] = sc.nextLong();
            arr2[i][1] = -sc.nextLong();
        }
        TreeSet<Long> result1 = new TreeSet<>();
        for (int i = 0; i < (1 << n1); i++) {
            long ans = 0;
            int x = i;
            for (int j = 0; j < n1; j++) {
                ans += arr1[j][x % 2];
                x >>= 1;
            }
            result1.add(ans);
        }
        TreeSet<Long> result2 = new TreeSet<>();
        for (int i = 0; i < (1 << n2); i++) {
            long ans = 0;
            int x = i;
            for (int j = 0; j < n2; j++) {
                ans += arr2[j][x % 2];
                x >>= 1;
            }
            result2.add(ans);
        }
        long ans = Long.MAX_VALUE;
        for (long x : result1) {
            Long ciel = result2.ceiling(-x);
            if (ciel != null) {
                ans = Math.min(ans, Math.abs(ciel + x));
            }
            Long floor = result2.floor(-x);
            if (floor != null) {
                ans = Math.min(ans, Math.abs(x + floor));
            }
        }
        System.out.println(ans);

    }
}
0