#include using namespace std; //*/ #include using namespace atcoder; //*/ #define rep(i,n) for(int i=0;i; using ll = long long; using ull = unsigned long long; //*/ template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } typedef pair pii; typedef pair pll; typedef vector vll; typedef vector vint; void solve(){ int n; cin >> n; vint p(n); rep(i,n) cin >> p[i]; fenwick_tree fw(n+1); int c = 0; deque ans; ans.push_back(p[0]); fw.add(p[0],1); rep(i,n-1){ int now = p[i+1]; int m = fw.sum(0,now); int M = ans.size()-m; //cout << "l : +" << m << " r : +" << M << endl; if(M > m){ c += m; ans.push_front(now); }else if(M < m){ c += M; ans.push_back(now); }else{ //cout << "! : " << now << endl; if(ans[0] > now) ans.push_front(now); else ans.push_back(now); c += m; } fw.add(now,1); } cout << c << endl; for(auto now : ans) cout << now << " "; cout << endl; //rep(i,ans.size()) cout << ans[i] << (ans.size()-1 == i ? "\n" : " "); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t = 1; cin >> t; rep(_,t) solve(); }