#include #include using namespace std; using namespace atcoder; void fast_io() { ios::sync_with_stdio(false); std::cin.tie(nullptr); } void solve() { int n; cin >> n; fenwick_tree fw(n + 2); deque ans; int inv = 0; for (int i = 0; i < n; i++) { int p; cin >> p; int l_cnt = fw.sum(0, p), r_cnt = fw.sum(p + 1, n + 2); if (l_cnt < r_cnt) { ans.push_front(p); inv += l_cnt; } else if (l_cnt > r_cnt) { ans.push_back(p); inv += r_cnt; } else if (p < ans.front()) { ans.push_front(p); inv += l_cnt; } else { ans.push_back(p); inv += r_cnt; } fw.add(p, 1); } cout << inv << "\n"; for (int i = 0; i < n; i++) { cout << ans[i] << (i + 1 == n ? "\n" : " "); } } int main() { fast_io(); int t; cin >> t; for (; t--;) { solve(); } }