結果

問題 No.198 キャンディー・ボックス2
ユーザー ty70ty70
提出日時 2015-05-28 18:05:31
言語 C++11
(gcc 11.4.0)
結果
TLE  
実行時間 -
コード長 2,017 bytes
コンパイル時間 647 ms
コンパイル使用メモリ 86,692 KB
実行使用メモリ 11,840 KB
最終ジャッジ日時 2023-09-20 17:10:03
合計ジャッジ時間 5,109 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 -- -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>	// require sort next_permutation count __gcd reverse etc.
#include <cstdlib>	// require abs exit atof atoi 
#include <cstdio>		// require scanf printf
#include <functional>
#include <numeric>	// require accumulate
#include <cmath>		// require fabs
#include <climits>
#include <limits>
#include <cfloat>
#include <iomanip>	// require setw
#include <sstream>	// require stringstream 
#include <cstring>	// require memset
#include <cctype>		// require tolower, toupper
#include <fstream>	// require freopen
#include <ctime>		// require srand
#define rep(i,n) for(int i=0;i<(n);i++)
#define ALL(A) A.begin(), A.end()
#define INF 1LL<<60

using namespace std;

typedef long long ll;
typedef pair<int, int> P;

ll C[12];

int N;
ll f(ll base ){
	ll curr = 0LL;
	rep (i, N ) curr += abs (C[i] - base );

	return curr;
}

ll ternary_search (ll lo, ll hi ){

	if (N == 1 ) return 0LL;

	int cnt = 1000;
	while (cnt-- ){
		ll cl = lo + (hi - lo )/3LL;
		ll ch = lo + 2LL*(hi - lo )/3LL; 
		if (f(cl) > f(ch) )
			lo = cl;
		else
			hi = ch;
	} // end while


	ll res = INF;
	for (ll base = max(lo-100LL, 0LL ); base <= hi; base++ ){
		ll curr = f(base );
		res = min (res, curr );
	} // end for

	return res;
}

ll linear_search (ll lo, ll hi ){

	if (N == 1 ) return 0LL;

	ll res = INF;
	for (ll base = lo; base <= hi; base++ ){
		ll curr = 0LL;
		rep (i, N ){
			curr += abs(C[i] - base );
		} // end rep
		res = min (res, curr );
	} // end for

	return res;
}

int main()
{
	memset (C, 0LL, sizeof (C ) );
	ios_base::sync_with_stdio(0);
	ll B; cin >> B;
	cin >> N;
	ll sum = B;
	rep (i, N ) cin >> C[i], sum += C[i];

	ll max_base = sum/(ll)N;

	ll lo = 0;
	ll hi = max_base + 1LL;

//	ll res1 = ternary_search (lo, hi );
//	cout << res1 << endl;

	ll res2 = linear_search (lo, hi );
	cout << res2 << endl;

//	cout << res1 << ' ' << res2 << endl;
	   
	return 0;
}
0