結果
| 問題 | 
                            No.2665 Minimize Inversions of Deque
                             | 
                    
| コンテスト | |
| ユーザー | 
                             hongrock
                         | 
                    
| 提出日時 | 2024-03-08 21:20:46 | 
| 言語 | C++17  (gcc 13.3.0 + boost 1.87.0)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 42 ms / 2,000 ms | 
| コード長 | 1,109 bytes | 
| コンパイル時間 | 2,052 ms | 
| コンパイル使用メモリ | 198,144 KB | 
| 最終ジャッジ日時 | 2025-02-20 02:06:15 | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge5 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 40 | 
ソースコード
#include<bits/stdc++.h>
using namespace std;
#define pb emplace_back
#define mp make_pair
 
using ll = long long;
using pii = pair<int,int>;
 
constexpr int mod = 998244353;
constexpr int inf = 0x3f3f3f3f;
constexpr int N = 2e5 + 10;
int T, n, s[N], p[N];
int lowbit(int x){
  return x & (-x);
}
void add(int x, int v){
  for(; x<=n; x+=lowbit(x)) s[x] += v;
}
int sum(int x){
  ll ret = 0;
  for(; x>0; x-=lowbit(x))  ret += s[x];
  return ret;
}
void _main(){
  cin >> T;
  while(T--){
    cin >> n;
    for(int i=1; i<=n; ++i) s[i] = 0;
    deque<int> Q;
    ll ans = 0;
    for(int i=1; i<=n; ++i){
      cin >> p[i];
      int c1 = sum(p[i]);
      int c2 = i - 1 - c1;
      if(c1 < c2 || (c1 == c2 && !Q.empty() && p[i] < Q.front())){
        Q.push_front(p[i]);
        ans += c1;
      } else {
        Q.push_back(p[i]);
        ans += c2;
      }
      add(p[i], 1);
    }
    cout << ans << '\n';
    for(int i=1; i<=n; ++i){
      cout << Q.front() << " \n"[i == n];
      Q.pop_front();
    }
  }
}
int main(){
  ios::sync_with_stdio(0);
  cin.tie(0); cout.tie(0);
  _main();
  return 0;
}
            
            
            
        
            
hongrock