結果

問題 No.198 キャンディー・ボックス2
ユーザー morishita4632morishita4632
提出日時 2020-05-16 23:35:41
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 1,000 ms
コード長 1,369 bytes
コンパイル時間 1,773 ms
コンパイル使用メモリ 170,344 KB
実行使用メモリ 4,348 KB
最終ジャッジ日時 2023-10-24 05:42:29
合計ジャッジ時間 3,323 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define int long long
typedef long long ll;
#define double long double
typedef double ld;
const double EPS = 1e-9;

/*
  上に凸な関数fに対し
    argmax f(x)
  を返す

  ※凸関数でないとダメ
   誤差で死にがち
 */
const double Golden = 2.0 / (3.0 + sqrt(5));

template <typename T>
T f(T trial);
int golden_search(int l, int r) {
  bool isMax = (f((ld)l - EPS) < f((ld)l));
  int cnt = 100;
  double cl = l + Golden * (r - l), cr = r - Golden * (r - l);
  double fc = f(cl), fd = f(cr);
  while (cr - cl > EPS && cnt-- > 0) {
    if (isMax ? (fc < fd) : (fc > fd)) {
      l = cl, cl = cr, cr = r - Golden * (r - l);
      fc = fd, fd = f(cr);
    } else {
      r = cr, cr = cl, cl = l + Golden * (r - l);
      fd = fc, fc = f(cl);
    }
  }

  int c1 = (cl + cr) / 2.0, c2 = c1 + 1;
  int ans = !(isMax ^ (f(c1) > f(c2))) ? c1 : c2;
  return ans;
}

int B, N;
vector<int> C;
template <typename T>
T f(T trial) {
  T cnt = 0;
  rep(i, N) {
    cnt += abs(trial - C[i]);
  }
  return cnt;
}

/*
https://yukicoder.me/problems/no/198
*/

signed main() {
  cin >> B >> N;
  C = vector<int>(N);
  int mx = B;
  rep(i, N) {
    cin >> C[i];
    mx += C[i];
  }
  mx /= N;


  int c = golden_search(0ll, mx);
  int ans = f(c);
  cout << ans << endl;
}
0