#include<bits/stdc++.h>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
using ll = long long;
#define int ll
const int SZ = 4e6;
const int N = 1e5 + 1;
int sz = 0;
int sm[SZ], L[SZ], R[SZ];
int a[N], pref[N];
ll ans[N];
int rigt[N];
set<int> st;
multiset<ll> vals;
int n;
void build(int t, int l = 0, int r = n - 1) {
if (l == r) return;
L[t] = sz++;
R[t] = sz++;
int m = (l + r) / 2;
build(L[t], l, m);
build(R[t], m + 1, r);
}
int update(int t, int k, int l = 0, int r = n - 1) {
int u = sz++;
L[u] = L[t];
R[u] = R[t];
sm[u] = sm[t] + 1;
if (l != r) {
int m = (l + r) / 2;
if (k <= m) L[u] = update(L[u], k, l, m);
else R[u] = update(R[u], k, m + 1, r);
}
return u;
}
int get(int t, int ql, int qr, int l = 0, int r = n - 1) {
if (ql <= l && r <= qr) return sm[t];
if (r < ql || qr < l) return 0;
int m = (l + r) / 2;
return get(L[t], ql, qr, l, m) + get(R[t], ql, qr, m + 1, r);
}
void solve() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i], --a[i];
}
pref[0] = 0;
sz = 1;
build(0);
for (int i = 0; i < n; ++i) {
pref[i + 1] = update(pref[i], a[i]);
}
st.insert(0);
rigt[0] = n - 1;
for (int i = 0; i < n; ++i) {
ans[0] += get(pref[i], a[i] + 1, n - 1);
}
vals.clear();
for (int i = 0; i < n; ++i) vals.insert(ans[i]);
auto upd = [&](int k, ll x) -> void {
vals.extract(ans[k]);
vals.insert(ans[k] = x);
};
ll z = *prev(vals.end());
for (int _ = 0; _ < n; ++_) {
cout << z << ' ';
int k_; cin >> k_;
k_ ^= z;
int k = k_ - 1;
int l = *prev(st.upper_bound(k));
int r = rigt[l];
ll cur = ans[l];
upd(k, 0);
st.erase(l);
if (k - l < r - k) {
if (k != l) {
ll cc = 0;
for (int i = l; i < k; ++i) {
cc += get(pref[i], a[i] + 1, n - 1) - get(pref[l], a[i] + 1, n - 1);
}
upd(l, cc);
rigt[l] = k - 1;
st.insert(l);
}
if (k != r) {
ll cc = cur;
for (int i = l; i <= k; ++i) {
cc -= get(pref[r + 1], 0, a[i] - 1) - get(pref[i + 1], 0, a[i] - 1);
}
upd(k + 1, cc);
rigt[k + 1] = r;
st.insert(k + 1);
}
} else {
if (k != r) {
ll cc = 0;
for (int i = k + 1; i <= r; ++i) {
cc += get(pref[i], a[i] + 1, n - 1) - get(pref[k + 1], a[i] + 1, n - 1);
}
upd(k + 1, cc);
st.insert(k + 1);
rigt[k + 1] = r;
}
if (k != l) {
ll cc = cur;
for (int i = r; i >= k; --i) {
cc -= get(pref[i], a[i] + 1, n - 1) - get(pref[l], a[i] + 1, n - 1);
}
upd(l, cc);
st.insert(l);
rigt[l] = k - 1;
}
}
z = *prev(vals.end());
}
cout << '\n';
st.clear();
vals.clear();
for (int i = 0; i < sz; ++i) {
sm[i] = 0;
L[i] = R[i] = -1;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif
int t;
cin >> t;
while (t--)
solve();
}