#include #include #define rep(i,n) for(int i=0;i vi; typedef vector vl; typedef vector> vvi; typedef vector> vvl; typedef long double ld; typedef pair P; ostream& operator<<(ostream& os, const modint& a) {os << a.val(); return os;} template ostream& operator<<(ostream& os, const static_modint& a) {os << a.val(); return os;} template ostream& operator<<(ostream& os, const dynamic_modint& a) {os << a.val(); return os;} template istream& operator>>(istream& is, vector& v){int n = v.size(); assert(n > 0); rep(i, n) is >> v[i]; return is;} template ostream& operator<<(ostream& os, const pair& p){os << p.first << ' ' << p.second; return os;} template ostream& operator<<(ostream& os, const vector& v){int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "\n" : " "); return os;} template ostream& operator<<(ostream& os, const vector>& v){int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "\n" : ""); return os;} template void chmin(T& a, T b){a = min(a, b);} template void chmax(T& a, T b){a = max(a, b);} using S = long long; S op(S a, S b){ return a + b; } S e(){ return 0; } void solve(){ int n; cin >> n; vector p(n); cin >> p; rep(i, n) p[i]--; segtree seg(n); long long ans = 0; deque d; rep(i, n){ int x = p[i]; int left = seg.prod(0, x); int right = seg.prod(x + 1, n); if(left < right){ ans += left; d.push_front(x); }else{ ans += right; d.push_back(x); } seg.set(x, 1); } cout << ans << "\n"; for(auto x : d){ cout << x + 1 << ' '; } cout << "\n"; } int main(){ int t; cin >> t; rep(_, t) solve(); return 0; }