#include <bits/stdc++.h>
int dx[2] = {0, 1};
int dy[2] = {1, 0};
long long GCD(long long a, long long b) { return (a) ? GCD(b % a, a) : b; }
long long LCM(long long a, long long b) { return a * b / GCD(a, b); }
long long fastpow(long long b, long long p) {
  if (!p) return 1;
  long long ret = fastpow(b, p >> 1);
  ret *= ret;
  if (p & 1) ret *= b;
  return ret;
}
using namespace std;
long long n, m, k;
long long s[5005], tag[5005], c[5005];
void solve() {
  cin >> n;
  for (int i = 1; i < n + 1; i++) cin >> tag[i];
  for (int i = 1; i < n + 1; i++) cin >> s[i];
  long long iq = 0, ans = 0;
  long long i, j, k;
  long long maxi, maxid, cur = 1, oldcur;
  bool flag;
  for (i = 1; i <= n; i++) {
    cur = i;
    maxi = -1;
    flag = false;
    for (k = i - 1; k > 0; k--) {
      if (tag[k] == tag[i]) continue;
      if (maxi < abs(s[k] - s[i]) && iq < abs(c[i] - c[k]))
        maxi = abs(s[k] - s[i]), maxid = k, flag = true;
    }
    if (flag)
      iq = abs(c[i] - c[maxid]), ans += abs(s[i] - s[maxid]), cur = maxid;
    for (j = i + 1; j <= n; j++) {
      if (tag[cur] == tag[j] || iq >= abs(c[cur] - c[j])) continue;
      iq = abs(c[cur] - c[j]);
      ans += abs(s[cur] - s[j]);
      i = j;
      i--;
      break;
    }
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int TT = 1;
  cin >> TT;
  c[1] = 2;
  for (int i = 2; i < 5005; i++) c[i] = 2 * c[i - 1];
  while (TT--) {
    solve();
  }
}
