#include #include using namespace std; using ll = long long; #define rep(i, n) for (int i = 0; i < (int)(n); i++) void solve() { ll n; cin >> n; atcoder::fenwick_tree bit(n); ll cnt = 0; deque ans; rep(i, n) { ll p; cin >> p; if (i == 0) { bit.add(p - 1, 1); ans.push_back(p); continue; } ll low = bit.sum(0, p); ll high = i - low; bit.add(p - 1, 1); if (low == high) { cnt += low; if (p < ans.front()) { ans.push_front(p); } else { ans.push_back(p); } } else if (low < high) { cnt += low; ans.push_front(p); } else { cnt += high; ans.push_back(p); } } cout << cnt << '\n'; rep(i, n) cout << (i ? " " : "") << ans[i]; cout << '\n'; } int main() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); int T = 1; cin >> T; for (int t = 0; t < T; t++) { solve(); } return 0; }