結果

問題 No.2665 Minimize Inversions of Deque
ユーザー tnakao0123tnakao0123
提出日時 2024-04-25 19:24:25
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 54 ms / 2,000 ms
コード長 1,333 bytes
コンパイル時間 705 ms
コンパイル使用メモリ 59,760 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-25 19:24:36
合計ジャッジ時間 4,420 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,816 KB
testcase_01 AC 44 ms
6,940 KB
testcase_02 AC 45 ms
6,940 KB
testcase_03 AC 44 ms
6,940 KB
testcase_04 AC 46 ms
6,940 KB
testcase_05 AC 45 ms
6,940 KB
testcase_06 AC 44 ms
6,944 KB
testcase_07 AC 43 ms
6,940 KB
testcase_08 AC 43 ms
6,944 KB
testcase_09 AC 45 ms
6,940 KB
testcase_10 AC 43 ms
6,944 KB
testcase_11 AC 44 ms
6,940 KB
testcase_12 AC 43 ms
6,940 KB
testcase_13 AC 43 ms
6,944 KB
testcase_14 AC 44 ms
6,940 KB
testcase_15 AC 45 ms
6,940 KB
testcase_16 AC 46 ms
6,944 KB
testcase_17 AC 47 ms
6,940 KB
testcase_18 AC 44 ms
6,940 KB
testcase_19 AC 8 ms
6,940 KB
testcase_20 AC 3 ms
6,940 KB
testcase_21 AC 3 ms
6,944 KB
testcase_22 AC 3 ms
6,940 KB
testcase_23 AC 3 ms
6,940 KB
testcase_24 AC 3 ms
6,944 KB
testcase_25 AC 3 ms
6,940 KB
testcase_26 AC 2 ms
6,940 KB
testcase_27 AC 3 ms
6,940 KB
testcase_28 AC 3 ms
6,944 KB
testcase_29 AC 3 ms
6,944 KB
testcase_30 AC 50 ms
6,940 KB
testcase_31 AC 46 ms
6,940 KB
testcase_32 AC 47 ms
6,944 KB
testcase_33 AC 50 ms
6,944 KB
testcase_34 AC 48 ms
6,944 KB
testcase_35 AC 46 ms
6,944 KB
testcase_36 AC 45 ms
6,940 KB
testcase_37 AC 47 ms
6,940 KB
testcase_38 AC 54 ms
6,944 KB
testcase_39 AC 48 ms
6,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

/* -*- coding: utf-8 -*-
 *
 * 2665.cc:  No.2665 Minimize Inversions of Deque - yukicoder
 */

#include<cstdio>
#include<vector>
#include<deque>
#include<algorithm>
 
using namespace std;

/* constant */

const int MAX_N = 200000;

/* typedef */

typedef long long ll;
typedef deque<int> dqi;

template <typename T>
struct BIT {
  int n;
  vector<T> bits;
  
  BIT() {}
  BIT(int _n) { init(_n); }

  void init(int _n) {
    n = _n;
    bits.assign(n + 1, 0);
  }

  T sum(int x) {
    x = min(x, n);
    T s = 0;
    while (x > 0) {
      s += bits[x];
      x -= (x & -x);
    }
    return s;
  }

  void add(int x, T v) {
    if (x <= 0) return;
    while (x <= n) {
      bits[x] += v;
      x += (x & -x);
    }
  }
};

/* global variables */

int ps[MAX_N];
BIT<int> bit;

/* subroutines */

/* main */

int main() {
  int tn;
  scanf("%d", &tn);

  while (tn--) {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", ps + i);

    bit.init(n);
    dqi as;
    ll x = 0;

    for (int i = 0; i < n; i++) {
      int c0 = bit.sum(ps[i]), c1 = i - c0;
      if (c0 < c1) as.push_front(ps[i]), x += c0;
      else as.push_back(ps[i]), x += c1;
      bit.add(ps[i], 1);
    }

    printf("%lld\n", x);
    for (int i = 0; i < n; i++)
      printf("%d%c", as[i], (i + 1 < n) ? ' ' : '\n');
  }

  return 0;
}
0