#include <bits/stdc++.h>
using namespace std;
const long long N = 500005;
const long long mod = 1e9 + 7;
void solve() {
  long long x = 0, y = 0, c = 0, ans = 0;
  long long n, m, k;
  cin >> n;
  long long a[n], b[n];
  ans = mod;
  for (long long i = 0; i < n; ++i) {
    cin >> a[i];
    a[i]--;
  }
  for (long long i = 0; i < n; ++i) {
    cin >> b[i];
  }
  vector<bool> vis(n);
  for (long long i = 0; i < n; ++i) {
    if (vis[i]) continue;
    x = i;
    vector<long long> v;
    while (!vis[x]) {
      vis[x] = 1;
      v.push_back(x);
      x = a[x];
    }
    x = (long long)(v.size());
    for (long long j = 1; j <= x; ++j) {
      if (x % j > 0) continue;
      for (long long k = 0; k < j; k++) {
        bool flag = 1;
        for (long long pos = k; pos + j < x; pos += j) {
          if (b[v[pos]] != b[v[pos + j]]) flag = 0;
        }
        if (flag) {
          ans = min(ans, j);
          break;
        }
      }
    }
  }
  cout << ans << "\n";
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  int T;
  cin >> T;
  while (T--) solve();
  return 0;
}
