結果
| 問題 | 
                            No.2501 Maximum Inversion Number
                             | 
                    
| コンテスト | |
| ユーザー | 
                             emthrm
                         | 
                    
| 提出日時 | 2023-07-13 10:31:44 | 
| 言語 | C++23  (gcc 13.3.0 + boost 1.87.0)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 590 ms / 2,000 ms | 
| コード長 | 1,736 bytes | 
| コンパイル時間 | 900 ms | 
| コンパイル使用メモリ | 103,272 KB | 
| 実行使用メモリ | 5,376 KB | 
| 最終ジャッジ日時 | 2024-09-15 13:55:34 | 
| 合計ジャッジ時間 | 4,041 ms | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge4 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 17 | 
ソースコード
#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;
}
            
            
            
        
            
emthrm