結果

問題 No.2665 Minimize Inversions of Deque
ユーザー 👑 rin204
提出日時 2024-03-08 21:07:31
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 280 ms / 2,000 ms
コード長 1,366 bytes
コンパイル時間 350 ms
コンパイル使用メモリ 82,560 KB
実行使用メモリ 107,904 KB
最終ジャッジ日時 2024-09-29 18:51:03
合計ジャッジ時間 10,355 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #

class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0] * (n + 1)
        if n == 0:
            self.n0 = 0
        else:
            self.n0 = 1 << (n.bit_length() - 1)

    def sum_(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    def sum(self, l, r=-1):
        if r == -1:
            return self.sum_(l)
        else:
            return self.sum_(r) - self.sum_(l)

    def get(self, i):
        return self.sum(i, i + 1)

    def add(self, i, x):
        i += 1
        while i <= self.n:
            self.data[i] += x
            i += i & -i

    def lower_bound(self, x):
        if x <= 0:
            return 0
        i = 0
        k = self.n0
        while k > 0:
            if i + k <= self.n and self.data[i + k] < x:
                x -= self.data[i + k]
                i += k
            k //= 2
        return i + 1


def solve():
    n = int(input())
    P = list(map(int, input().split()))
    ans = 0
    bit = BIT(n + 1)
    L = []
    R = []
    for p in P:
        l = bit.sum(p)
        r = bit.sum(p + 1, n + 1)
        if l < r:
            ans += l
            L.append(p)
        else:
            ans += r
            R.append(p)
        bit.add(p, 1)

    print(ans)
    print(*(L[::-1] + R))


for _ in range(int(input())):
    solve()
0