#include #include using namespace std; using ll = long long; int N; int P[202020]; void solve(){ cin >> N; atcoder::fenwick_tree bt(N); deque ans; ll x = 0; for(int i = 0;i < N;i++){ int p; cin >> p; p--; int f = bt.sum(0, p), b = bt.sum(p, N); if(f > b){ ans.push_back(p + 1); }else if(f < b){ ans.push_front(p + 1); }else{ if(ans.size() && ans.front() > p){ ans.push_front(p + 1); }else{ ans.push_back(p + 1); } } x += min(f, b); bt.add(p, 1); } cout << x << endl; for(int i = 0;i < N;i++){ cout << ans.front() << " \n"[i + 1 == N]; ans.pop_front(); } } int main(void){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t--)solve(); return 0; }