結果

問題 No.2665 Minimize Inversions of Deque
ユーザー 矢澤式WINTER
提出日時 2024-03-08 22:53:53
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 95 ms / 2,000 ms
コード長 1,456 bytes
コンパイル時間 5,382 ms
コンパイル使用メモリ 313,020 KB
実行使用メモリ 6,820 KB
最終ジャッジ日時 2024-09-29 20:22:28
合計ジャッジ時間 8,933 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
//*/
#include <atcoder/all>
using namespace atcoder;
//*/
#define rep(i,n) for(int i=0;i<n;i++)
#define Rep(i,a,b) for(int i=a;i<b;i++)
#define ALL(x) (x).begin(),(x).end()
#define dbgv(x); for(auto now : x) cout << now << " "; cout << endl;
//using P = pair<int,int>;
using ll = long long;
using ull = unsigned long long;
//*/
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<ll> vll;
typedef vector<int> vint;


void solve(){
  int n; cin >> n;
  vint p(n); rep(i,n) cin >> p[i];
  fenwick_tree<int> fw(n+1);
  ll c = 0;
  deque<int> ans;
  ans.push_back(p[0]);
  fw.add(p[0],1);
  rep(i,n-1){
    int now = p[i+1];
    int m = fw.sum(0,now);
    int M = ans.size()-m;
    //cout << "l : +" << m << " r : +" << M << endl; 
    if(M > m){
      c += m;
      ans.push_front(now);
    }else if(M < m){
      c += M;
      ans.push_back(now);
    }else{
      //cout << "! : " << now << endl; 
      if(ans.front() > now) ans.push_front(now);
      else ans.push_back(now);
      c += m;
    }
    fw.add(now,1);
  }
  cout << c << endl;
  for(auto now : ans) cout << now << " "; cout << endl;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int t = 1; cin >> t;
  rep(_,t) solve();
}
0