結果

問題 No.198 キャンディー・ボックス2
ユーザー morishita4632morishita4632
提出日時 2020-05-17 14:33:39
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 1,000 ms
コード長 1,737 bytes
コンパイル時間 1,497 ms
コンパイル使用メモリ 169,316 KB
実行使用メモリ 4,372 KB
最終ジャッジ日時 2023-10-25 22:30:24
合計ジャッジ時間 2,818 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 AC 1 ms
4,372 KB
testcase_02 AC 2 ms
4,372 KB
testcase_03 AC 1 ms
4,372 KB
testcase_04 AC 2 ms
4,372 KB
testcase_05 AC 2 ms
4,372 KB
testcase_06 AC 1 ms
4,372 KB
testcase_07 AC 2 ms
4,372 KB
testcase_08 AC 2 ms
4,372 KB
testcase_09 AC 1 ms
4,372 KB
testcase_10 AC 1 ms
4,372 KB
testcase_11 AC 2 ms
4,372 KB
testcase_12 AC 2 ms
4,372 KB
testcase_13 AC 2 ms
4,372 KB
testcase_14 AC 2 ms
4,372 KB
testcase_15 AC 2 ms
4,372 KB
testcase_16 AC 2 ms
4,372 KB
testcase_17 AC 1 ms
4,372 KB
testcase_18 AC 2 ms
4,372 KB
testcase_19 AC 2 ms
4,372 KB
testcase_20 AC 1 ms
4,372 KB
testcase_21 AC 2 ms
4,372 KB
testcase_22 AC 2 ms
4,372 KB
testcase_23 AC 1 ms
4,372 KB
testcase_24 AC 1 ms
4,372 KB
testcase_25 AC 1 ms
4,372 KB
testcase_26 AC 2 ms
4,372 KB
testcase_27 AC 2 ms
4,372 KB
testcase_28 AC 2 ms
4,372 KB
testcase_29 AC 2 ms
4,372 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/min f(x)
  を返す。
  引数は、(傾き正, 傾き負)の順に与える(minのとき注意)。
  このとき右側の点は+1しておく(開区間)

  傾きが0の点を探せばよいので、傾きで2分探索をする

  ※凸関数でないとダメ
   極値を挟んだ値を渡していることを確認
   intのまま扱うのでmod計算もできる
   intの問題でもdoubleに焼き直した方が良い場合もある
   inc, decはそれぞれ「1つ前に比べて増加, 減少している点」を表す
   極値が平らな場合、デフォルトでは
    ・max...最も左の点
    ・min...最も右の点
   を返す。入れ替えるにはfの差の部分の不等号に等号を加える。
 */

#pragma region golden_search
const double Golden = 2.0 / (3.0 + sqrt(5));

int f(int trial);
int slope_search(int inc, int dec) {
  bool isMax = inc < dec;
  while (abs(dec - inc) > 1) {
    int mid = (inc + dec) / 2;
    (f(mid) - f(mid - 1) > 0 ? inc : dec) = mid;
  }
  return isMax ? inc : dec;
}
#pragma endregion

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

int B, N;
vector<int> C;

int f(int trial) {
  int cnt = 0;
  rep(i, N) {
    cnt += abs(trial - C[i]);
  }
  return cnt;
}

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 = slope_search(mx + 1, 0);  // mx側は開区間で。
  int ans = f(c);
  cout << ans << endl;
}
0