#include #include #include #include std::pair> solve(int n, const std::vector& p) { long long inv = 0; std::deque a; atcoder::fenwick_tree ft(n); for (int i = 0; i < n; ++i) { const int cnt_lt = ft.sum(0, p[i]); const int cnt_gt = i - cnt_lt; ft.add(p[i], 1); const bool ok_l = cnt_lt <= cnt_gt; const bool ok_r = cnt_lt >= cnt_gt; if (ok_l and ok_r) { if (a.empty() or a.front() < p[i]) { a.push_back(p[i]); } else { a.push_front(p[i]); } } else if (ok_l) { a.push_front(p[i]); } else if (ok_r) { a.push_back(p[i]); } else { assert(false); } inv += std::min(cnt_lt, cnt_gt); } return { inv, std::vector(a.begin(), a.end()) }; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int t; std::cin >> t; while (t--) { int n; std::cin >> n; std::vector p(n); for (auto&& e : p) std::cin >> e, --e; auto [inv, a] = solve(n, p); std::cout << inv << '\n'; for (int i = 0; i < n; ++i) { if (i) std::cout << ' '; std::cout << a[i] + 1; } std::cout << '\n'; } }