結果
| 問題 |
No.198 キャンディー・ボックス2
|
| コンテスト | |
| ユーザー |
ty70
|
| 提出日時 | 2015-05-28 19:08:16 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
AC
|
| 実行時間 | 2 ms / 1,000 ms |
| コード長 | 2,478 bytes |
| コンパイル時間 | 960 ms |
| コンパイル使用メモリ | 91,236 KB |
| 実行使用メモリ | 5,248 KB |
| 最終ジャッジ日時 | 2024-11-16 09:04:28 |
| 合計ジャッジ時間 | 1,891 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
#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 B ){
ll curr = 0LL;
rep (i, N ) {
if (C[i] - base >= 0 ){
curr += C[i] - base;
B += C[i] - base;
}else{
if (B >= base - C[i] ){
curr += base - C[i];
B -= base - C[i];
}else{
curr = INF;
break;
} // end if
} // end if
} // end rep
return curr;
}
ll ternary_search (ll lo, ll hi, ll B ){
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, B ) > f(ch, B ) )
lo = cl;
else
hi = ch;
} // end while
ll res = INF;
for (ll base = max(lo-100LL, 0LL ); base <= hi; base++ ){
ll curr = f(base, B );
res = min (res, curr );
} // end for
return res;
}
ll linear_search (ll lo, ll hi, ll B ){
if (N == 1 ) return 0LL;
ll res = INF;
for (ll base = lo; base <= hi; base++ ){
ll curr = 0LL;
ll b = B;
rep (i, N ){
if (C[i] - base >= 0 ){
curr += (C[i] - base );
b += (C[i] - base);
}else{
if (b >= base - C[i] ){
curr += (base - C[i] );
b -= (base - C[i] );
}else{
curr = INF;
break;
} // end if
} // edn if
} // 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];
sort (C, C+N, greater<ll>() );
ll max_base = sum/(ll)N;
ll lo = 0;
ll hi = max_base + 1LL;
ll res1 = ternary_search (lo, hi, B );
cout << res1 << endl;
// ll res2 = linear_search (lo, hi, B );
// cout << res2 << endl;
return 0;
}
ty70