結果

問題 No.198 キャンディー・ボックス2
ユーザー Grenache
提出日時 2016-02-15 20:58:40
言語 Java
(openjdk 23)
結果
AC  
実行時間 134 ms / 1,000 ms
コード長 1,293 bytes
コンパイル時間 3,811 ms
コンパイル使用メモリ 78,032 KB
実行使用メモリ 54,276 KB
最終ジャッジ日時 2024-11-16 09:54:31
合計ジャッジ時間 9,042 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.Scanner;


public class Main_yukicoder198 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int b = sc.nextInt();
        int n = sc.nextInt();
        int[] c = new int[n];
        long sum = 0;
        for (int i = 0; i < n; i++) {
        	c[i] = sc.nextInt();
        	sum += c[i];
        }
        Arrays.sort(c);

        long l = 0;
        long r = 1_000_000_000;
        while (r - l > 5) {
        	long c1 = (l + l + r) / 3;
        	long c2 = (l + r + r) / 3;

        	if (f(c1, b, n, c, sum) > f(c2, b, n, c, sum)) {
        		l = c1;
        	} else {
        		r = c2;
        	}
        }

        long min = Long.MAX_VALUE;
//        long mini = 0;
        for (long i = l; i <= r; i++) {
        	long tmp = f(i, b, n, c, sum);
        	if (tmp < min) {
        		min = tmp;
//        		mini = i;
        	}
        }

        System.out.println(min);
//        System.out.println(mini);

        sc.close();
    }

	private static long f(long x, int b, int n, int[] c, long sum) {
		if (n == 1) {
			return 0;
		}

		if (x * n > sum + b) {
			return Long.MAX_VALUE;
		}

		long ret = 0;
		for (int i = n - 1; i >= 0; i--) {
			ret += Math.abs(c[i] - x);
		}

		return ret;
	}
}
0