#include using namespace std; using uint = unsigned int; using ll = long long; using ull = unsigned long long; template using V = vector; template using VV = V>; template using VVV = V>; template using VVVV = VV>; #define rep(i,n) for(ll i=0ll;i void chmin(T& t, const U& u) { if (t > u) t = u; } template void chmax(T& t, const U& u) { if (t < u) t = u; } // cin.tie(nullptr); // ios::sync_with_stdio(false); // cout << fixed << setprecision(20); template struct SegmentTree { vector seg; ll seg_size;//葉の数 SegmentTree(ll N) : seg(4*N, E()), seg_size() { seg_size = 1; while(seg_size < N) seg_size *= 2; } SegmentTree(const vector a) : seg(4*a.size(), E()), seg_size() { ll N = a.size(); seg_size = 1; while(seg_size < N) seg_size *= 2; rep(i,N) seg[i + seg_size - 1] = a[i]; for(ll i = seg_size-2; i >= 0; i --){ seg[i] = OP(seg[2*i + 1], seg[2*i + 2]); } } void update(ll idx, T x){ idx += seg_size - 1; seg[idx] = x; while(idx > 0){ idx = (idx - 1) / 2; seg[idx] = OP(seg[2*idx + 1], seg[2*idx + 2]); } } T quere(ll a, ll b) { return quere_sub(a, b, 0, 0, seg_size); } T quere_sub(ll a, ll b, ll idx, ll left, ll right){ if(a >= right || b <= left) return E(); if(a <= left && b >= right) return seg[idx]; T v1 = quere_sub(a, b, 2 * idx + 1, left, (left + right) / 2); T v2 = quere_sub(a, b, 2 * idx + 2, (left + right) / 2, right); return OP(v1, v2); } }; template S e(){return 0;} template S op(S L, S R){return L+R;} void solve(){ ll n; cin >> n; SegmentTree seg(n+1); deque dq; ll ans = 0; rep(i, n){ ll a; cin >> a; ll f = seg.quere(0, a); ll b = seg.quere(a+1, n+1); seg.update(a, 1); ans += min(f, b); if(f < b || dq.empty()) dq.push_front(a); else if(f > b || dq.front() < a) dq.push_back(a); else dq.push_front(a); } cout << ans << endl; for(auto a:dq) cout << a << " "; cout << endl; } int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int t=1; cin >> t; rep(i,t) solve(); }