/* -*- coding: utf-8 -*- * * 2665.cc: No.2665 Minimize Inversions of Deque - yukicoder */ #include #include #include #include using namespace std; /* constant */ const int MAX_N = 200000; /* typedef */ typedef long long ll; typedef deque dqi; template struct BIT { int n; vector 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 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; }