#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int N = 2e5 + 100;
const long long inf = 1e18;
long long p[N], c[N], t, n;
vector<long long> cols;
long long ans;
bool visited[N], bv[N];
long long cs;
void dfs(long long i) {
  cols.push_back(c[i]);
  visited[i] = 1;
  if (visited[p[i]]) return;
  dfs(p[i]);
}
void check(long long dist, long long j) {
  if (bv[j]) return;
  long long cval = j;
  bv[cval] = 1;
  bool ok = 1;
  cval += dist;
  cval %= cs;
  while (cval != j) {
    bv[cval] = 1;
    if (cols[j] != cols[cval]) {
      ok = 0;
      break;
    }
    cval += dist;
    cval %= cs;
  }
  if (ok) ans = min(ans, dist - 1);
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> t;
  while (t--) {
    cin >> n;
    ans = inf;
    for (long long i = 1; i <= n; i++) {
      cin >> p[i];
      visited[i] = 0;
      bv[i] = 0;
    }
    for (long long i = 1; i <= n; i++) cin >> c[i];
    cols.clear();
    for (long long i = 1; i <= n; i++) {
      if (visited[i]) continue;
      dfs(i);
      ans = min(ans, (long long)(cols.size() - 1));
      cs = cols.size();
      for (long long k = 1; k * k <= cols.size(); k++) {
        if (cs % k == 0) {
          for (long long j = 0; j < cols.size(); j++) {
            check(k, j);
          }
          for (long long j = 0; j < cols.size(); j++) bv[j] = 0;
          for (long long j = 0; j < cols.size(); j++) {
            check(cs / k, j);
          }
          for (long long j = 0; j < cols.size(); j++) bv[j] = 0;
        }
      }
      cols.clear();
    }
    cout << ans + 1 << endl;
  }
}
