#include using namespace std; using ll = long long; using lll = __int128; using P = pair; #define fix(x) fixed << setprecision(x) #define asc(x) x, vector, greater #define rep(i, n) for(ll i = 0; i < n; ++i) #define all(x) (x).begin(),(x).end() templatebool chmin(T&a, const T&b){if(a>b){a=b;return 1;}return 0;} templatebool chmax(T&a, const T&b){if(a struct BIT{ int n; vector data; BIT(int n=0) : n(n), data(n+1){} T sum(int i){ T res = 0; for(; i; i -= i&-i){ res += data[i]; } return res; } void add(int i, T x){ for(; i <= n; i += i&-i){ data[i] += x; } } int lower_bound(T w){ int x = 0, r = 1; while(r0;l>>=1){ if(x+l<=n && data[x+l]> t; while(t--){ int n; cin >> n; BIT bit(n); ll ans = 0; deque que; rep(i,n){ int a; cin >> a; int l = bit.sum(a), r = i-l; if(lr){ que.push_back(a); ans += r; }else{ if(que.front()>a) que.push_front(a); else que.push_back(a); ans += l; } bit.add(a,1); } cout << ans << '\n'; rep(i,n){ cout << que.front() << " "; que.pop_front(); } cout << '\n'; } return 0; }