#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 using namespace std; template struct BinaryIndexedTree { int N; vectorbit; BinaryIndexedTree(){} BinaryIndexedTree(int x) { N = x; bit.resize(x+1); } void add(int x,T y) { x++; while(x <= N) { bit[x] += y; x += x&-x; } } T sum(int x) { x++; T res = 0; while(x) { res += bit[x]; x -= x&-x; } return res; } inline T sum(int l, int r) {//[l,r) return sum(r-1)-sum(l-1); } inline T operator[](int k) { return sum(k)-sum(k-1); } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t--) { int n; cin >> n; vectorp(n); BinaryIndexedTreebit(n+1); dequeans; long long fans = 0; for(int i = 0; i < n; i++) { cin >> p[i]; int a = bit.sum(0,p[i]); int b = bit.sum(p[i],n+1); bit.add(p[i],1); fans += min(a,b); if(a < b) { ans.push_front(p[i]); } else if(b > a) { ans.push_back(p[i]); } else if(ans.empty() || ans.front() > p[i]) { ans.push_front(p[i]); } else { ans.push_back(p[i]); } } cout << fans << "\n"; while(!ans.empty()) { cout << ans.front() << ((ans.size() == 1)?"\n":" "); ans.pop_front(); } } }