結果

問題 No.2665 Minimize Inversions of Deque
ユーザー haihamabossuhaihamabossu
提出日時 2024-03-08 21:57:06
言語 C++17(gcc12)
(gcc 12.3.0 + boost 1.87.0)
結果
AC  
実行時間 46 ms / 2,000 ms
コード長 994 bytes
コンパイル時間 2,358 ms
コンパイル使用メモリ 207,412 KB
実行使用メモリ 6,820 KB
最終ジャッジ日時 2024-09-29 19:36:38
合計ジャッジ時間 6,041 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <atcoder/fenwicktree>
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

void solve() {
  ll n;
  cin >> n;
  atcoder::fenwick_tree<ll> bit(n);
  ll cnt = 0;
  deque<ll> ans;
  rep(i, n) {
    ll p;
    cin >> p;
    if (i == 0) {
      bit.add(p - 1, 1);
      ans.push_back(p);
      continue;
    }
    ll low = bit.sum(0, p);
    ll high = i - low;
    bit.add(p - 1, 1);
    if (low == high) {
      cnt += low;
      if (p < ans.front()) {
        ans.push_front(p);
      } else {
        ans.push_back(p);
      }
    } else if (low < high) {
      cnt += low;
      ans.push_front(p);
    } else {
      cnt += high;
      ans.push_back(p);
    }
  }
  cout << cnt << '\n';
  rep(i, n) cout << (i ? " " : "") << ans[i];
  cout << '\n';
}

int main() {
  std::cin.tie(nullptr);
  std::ios_base::sync_with_stdio(false);
  int T = 1;
  cin >> T;
  for (int t = 0; t < T; t++) {
    solve();
  }
  return 0;
}
0