#pragma GCC optimize("O2") #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define int ll #define INT128_MAX (__int128)(((unsigned __int128) 1 << ((sizeof(__int128) * __CHAR_BIT__) - 1)) - 1) #define INT128_MIN (-INT128_MAX - 1) #define clock chrono::steady_clock::now().time_since_epoch().count() #ifdef DEBUG #define dbg(x) cout << (#x) << " = " << x << '\n' #else #define dbg(x) #endif namespace R = std::ranges; namespace V = std::views; using namespace std; using ll = long long; using ull = unsigned long long; using ldb = long double; using pii = pair; using pll = pair; //#define double ldb template ostream& operator<<(ostream& os, const pair pr) { return os << pr.first << ' ' << pr.second; } template ostream& operator<<(ostream& os, const array &arr) { for(const T &X : arr) os << X << ' '; return os; } template ostream& operator<<(ostream& os, const vector &vec) { for(const T &X : vec) os << X << ' '; return os; } template ostream& operator<<(ostream& os, const set &s) { for(const T &x : s) os << x << ' '; return os; } template struct fenwickTree { const int size; vector data; fenwickTree(int _size) : size(_size + 1), data(_size + 1) {} fenwickTree(vector &init) : size(ssize(init) + 1), data(ssize(init) + 1) { partial_sum(init.begin(), init.end(), data.begin() + 1); for(int i = size - 1; i > 0; i--) data[i] -= data[i - (i & (-i))]; } void add(int i, T d) { for(i += 1; i < size; i += i & (-i)) data[i] += d; } T query(int i) { T res = T(0); for(i += 1; i > 0; i -= i & (-i)) res += data[i]; return res; } T query(int l, int r) { return query(r - 1) - query(l - 1); } }; signed main() { ios::sync_with_stdio(false), cin.tie(NULL); int t; cin >> t; while(t--) { int n; cin >> n; vector p(n); for(int &x : p) { cin >> x; x--; } deque dq; dq.push_front(p[0]); fenwickTree ft(n); ft.add(p[0], 1); int inv = 0; for(int i = 1; i < n; i++) { int lc = ft.query(p[i]); int rc = i - lc; inv += min(lc, rc); if (lc < rc or (lc == rc and p[i] < dq.front())) dq.push_front(p[i]); else dq.push_back(p[i]); ft.add(p[i], 1); } cout << inv << '\n'; for(int x : dq) cout << x + 1 << ' '; cout << '\n'; } return 0; }