結果

問題 No.198 キャンディー・ボックス2
ユーザー kou6839
提出日時 2015-04-29 18:54:40
言語 Java
(openjdk 23)
結果
AC  
実行時間 134 ms / 1,000 ms
コード長 904 bytes
コンパイル時間 2,362 ms
コンパイル使用メモリ 76,992 KB
実行使用メモリ 41,376 KB
最終ジャッジ日時 2024-11-16 09:02:46
合計ジャッジ時間 6,631 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Scanner;


public class Main {
	public static void main(String[] args){
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);
		long B = sc.nextLong();
		long N = sc.nextLong();
		long[] can = new long[(int)N];
		for(int i=0;i<N;i++){
			can[i]=sc.nextInt();
		}
		long l = -1;long r=1000000000000L;
		while(r-l>2){
			long lm=(2*l+r)/3, rm=(l+2*r)/3;
			long lsum=0,rsum=0;
			for(int i=0;i<N;i++){
				lsum+=lm-can[i];
			}

			for(int i=0;i<N;i++){
				rsum+=rm-can[i];
			}
			long ll=0,rr=0;
			for(int i=0;i<N;i++){
				ll+=Math.abs(lm-can[i]);
			}
			for(int i=0;i<N;i++){
				rr+=Math.abs(rm-can[i]);
			}
			if(lsum>B){
				r=lm;
			}else if(rsum>B){
				r=rm;
			}else if(ll<=rr){
				r=rm;
			}else{
				l=lm;
			}
		}
		long ans=0;
		for(int i=0;i<N;i++){
			ans+=Math.abs((r+l)/2-(long)can[i]);
		}
		System.out.println(ans);
	}
}
0