結果

問題 No.198 キャンディー・ボックス2
ユーザー YamaKasaYamaKasa
提出日時 2018-08-09 20:06:41
言語 Java21
(openjdk 21)
結果
AC  
実行時間 134 ms / 1,000 ms
コード長 996 bytes
コンパイル時間 1,946 ms
コンパイル使用メモリ 77,620 KB
実行使用メモリ 57,752 KB
最終ジャッジ日時 2023-10-24 12:35:39
合計ジャッジ時間 6,819 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 116 ms
54,164 KB
testcase_01 AC 128 ms
57,700 KB
testcase_02 AC 130 ms
57,752 KB
testcase_03 AC 126 ms
57,340 KB
testcase_04 AC 126 ms
57,096 KB
testcase_05 AC 125 ms
57,112 KB
testcase_06 AC 125 ms
57,564 KB
testcase_07 AC 134 ms
56,968 KB
testcase_08 AC 126 ms
57,676 KB
testcase_09 AC 127 ms
57,304 KB
testcase_10 AC 130 ms
57,096 KB
testcase_11 AC 129 ms
57,436 KB
testcase_12 AC 120 ms
56,304 KB
testcase_13 AC 126 ms
57,592 KB
testcase_14 AC 132 ms
57,720 KB
testcase_15 AC 134 ms
57,356 KB
testcase_16 AC 128 ms
57,488 KB
testcase_17 AC 127 ms
57,372 KB
testcase_18 AC 128 ms
57,472 KB
testcase_19 AC 116 ms
56,112 KB
testcase_20 AC 129 ms
57,448 KB
testcase_21 AC 127 ms
57,636 KB
testcase_22 AC 130 ms
57,520 KB
testcase_23 AC 127 ms
57,528 KB
testcase_24 AC 127 ms
57,624 KB
testcase_25 AC 128 ms
57,348 KB
testcase_26 AC 127 ms
57,620 KB
testcase_27 AC 122 ms
56,244 KB
testcase_28 AC 128 ms
57,600 KB
testcase_29 AC 128 ms
57,560 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		long B = scan.nextLong();
		int N = scan.nextInt();
		long[] C = new long[N];
		long sum = B;
		for(int i = 0; i < N; i++) {
			C[i] = scan.nextLong();
			sum += C[i];
		}
		scan.close();
		if(N == 1) {
			System.out.println("0");
			System.exit(0);
		}
		long r = sum / N;
		long l = 0;

		long min = Long.MAX_VALUE;
		while(r - l > 3) {
			// 幅 len = (r - l) / 3
			// x1 = l + len = (2l + r) / 3
			// x2 = x1 + len = (l + 2r) / 3
			long x1 = (l * 2 + r) / 3;
			long x2 = (l + r * 2) / 3;
			long t1 = 0;
			long t2 = 0;
			for(int i = 0; i < N; i++) {
				t1 += Math.abs(x1 - C[i]);
				t2 += Math.abs(x2 - C[i]);
			}
			if(t1 > t2) {
				l = x1;
			}else {
				r = x2;
			}
		}
		for(long i = l; i <= r; i++) {
			long t = 0;
			for(int j = 0; j < N; j++) {
				t += Math.abs(i - C[j]);
			}
			min = Math.min(min, t);
		}
		System.out.println(min);
	}
}
0