結果

問題 No.2501 Maximum Inversion Number
ユーザー 👑 emthrmemthrm
提出日時 2023-07-13 10:31:44
言語 C++23
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 552 ms / 2,000 ms
コード長 1,736 bytes
コンパイル時間 935 ms
コンパイル使用メモリ 103,392 KB
実行使用メモリ 4,764 KB
最終ジャッジ日時 2023-10-13 18:04:41
合計ジャッジ時間 4,099 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,352 KB
testcase_01 AC 80 ms
4,356 KB
testcase_02 AC 180 ms
4,352 KB
testcase_03 AC 109 ms
4,352 KB
testcase_04 AC 88 ms
4,684 KB
testcase_05 AC 90 ms
4,764 KB
testcase_06 AC 95 ms
4,652 KB
testcase_07 AC 98 ms
4,352 KB
testcase_08 AC 101 ms
4,352 KB
testcase_09 AC 82 ms
4,348 KB
testcase_10 AC 97 ms
4,352 KB
testcase_11 AC 72 ms
4,352 KB
testcase_12 AC 71 ms
4,352 KB
testcase_13 AC 2 ms
4,348 KB
testcase_14 AC 119 ms
4,588 KB
testcase_15 AC 76 ms
4,348 KB
testcase_16 AC 552 ms
4,352 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

std::int64_t NChoose2(const int n) { return std::int64_t{n} * (n - 1) / 2; }

// <AC>
// 二分探索で t_0 を求める。
std::int64_t Solve(
    int m, const std::vector<int>& l, const std::vector<int>& r) {
  const int n = l.size();
  assert(std::ssize(r) == n);

  if (std::reduce(l.begin(), l.end(), INT64_C(0)) > m) return -1;

  int t0 = m + 1;  // 解説の値に +1 している
  for (int lbound = 0; lbound + 1 < t0;) {
    const int t = std::midpoint(lbound, t0);
    std::int64_t length = 0;
    for (int i = 0; i < n; ++i) {
      length += std::clamp(t, l[i], r[i]);
    }
    (length >= m ? t0 : lbound) = t;
  }
  if (t0 > m) return -1;

  std::int64_t ans = NChoose2(m);
  int num_of_t0 = 0;
  for (int i = 0; i < n; ++i) {
    const int c_i = std::clamp(t0, l[i], r[i]);
    m -= c_i;
    ans -= NChoose2(c_i);
    // 一旦個数を t0 にする
    if (l[i] < t0 && t0 <= r[i]) ++num_of_t0;
  }
  assert(m <= 0 && -m <= num_of_t0);
  ans -= (NChoose2(t0 - 1) - NChoose2(t0)) * -m;  // 最後に調節する
  return ans;
}

int main() {
  constexpr int kMaxT = 200000, kMaxN = 200000, kMaxM = 1000000000;

  int t;
  std::cin >> t;
  assert(1 <= t && t <= kMaxT);

  while (t--) {
    int n, m;
    std::cin >> n >> m;
    assert(1 <= n && n <= kMaxN && 1 <= m && m <= kMaxM);
    std::vector<int> l(n);
    for (int i = 0; i < n; ++i) {
      std::cin >> l[i];
    }
    std::vector<int> r(n);
    for (int i = 0; i < n; ++i) {
      std::cin >> r[i];
      assert(0 <= l[i] && l[i] <= r[i] && r[i] <= kMaxM);
    }
    std::cout << Solve(m, l, r) << '\n';
  }
  return 0;
}
0