結果

問題 No.2665 Minimize Inversions of Deque
ユーザー srjywrdnprkt
提出日時 2024-03-09 23:23:56
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 107 ms / 2,000 ms
コード長 1,851 bytes
コンパイル時間 2,189 ms
コンパイル使用メモリ 201,388 KB
最終ジャッジ日時 2025-02-20 03:33:15
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

//RSQ (0-indexed)
template<class T> struct BIT {
    private:
        vector<T> bit; int N;
        T _sum(int r){
            r++; T res = 0;
            while(r > 0) res += bit[r-1], r -= r & -r;
            return res;
        }

    public:
        BIT (int n){ N = n; bit.resize(N);}
        BIT (vector<T> &a) : BIT(a.size()) { for (int i=0; i<N; i++) add(i, a[i]);}
        void add(int loc, T val){
            loc++;
            while(loc <= N) bit[loc-1] += val, loc += loc & -loc;
        }
        void change(int loc, T val){add(loc, -get(loc)+val);}
        T sum(int l, int r) {return _sum(r) - _sum(l-1);}
        T get(int l) {return sum(l, l);}
        void clear() {for (int i=0; i<N; i++) bit[i] = 0;}
};

void solve(){
    ll N, S, T;
    cin >> N;
    //転倒数はすでに出てきた数のみに依存する→その時点で転倒数を最小にするのが最適
    //転倒数が同じになるなら、先頭の要素と比較する
    vector<ll> P(N+1);
    for (int i=1; i<=N; i++) cin >> P[i];
    BIT<ll> bit(N+1);
    deque<ll> que;  
    for (int i=1; i<=N; i++){
        S = bit.sum(1, P[i]); //P以下
        T = i-1-S; //P以上
        if (S < T) que.push_front(P[i]);
        else if (S > T) que.push_back(P[i]);
        else{
            if (que.empty() || que.front() < P[i]) que.push_back(P[i]);
            else que.push_front(P[i]);
        }
        bit.add(P[i], 1);
    }
    ll ans=0;
    bit.clear();
    for (int i=0; i<N; i++){
        ans += bit.sum(que[i]+1, N);
        bit.add(que[i], 1);
    }
    cout << ans << endl;
    for (auto x : que) cout << x << " ";
    cout << endl;
}

int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);

    int T;
    cin >> T;
    while(T--) solve();

    return 0;
}
0