#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return a % b ? gcd(b, a % b) : b; }
const long long mod = 998244353;
const long long inf = 0x3f3f3f3f;
long long qpow(long long a, long long b) {
  long long t = 1;
  while (b != 0) {
    if (b & 1) t = (t * a) % mod;
    a = (a * a) % mod;
    b >>= 1;
  }
  return t;
}
template <typename T>
void re(T& a) {
  for (auto& t : a) cin >> t;
}
template <typename T>
void pr(T& a) {
  for (auto& t : a) cout << t << " ";
  cout << endl;
}
const int N = 2e5 + 5;
int p[N];
int c[N];
int in[N];
int col[N];
vector<int> e[N];
int n, cnt, mi;
void dfs(int u, int f) {
  if (u == f) {
    return;
  }
  col[u] = cnt;
  e[cnt].push_back(c[u]);
  dfs(p[u], f);
}
void topo() {
  queue<int> q;
  for (int i = 1; i <= cnt; ++i) {
    e[i].clear();
  }
  cnt = 0;
  for (int i = 1; i <= n; ++i) {
    in[i] = 0;
    col[i] = 0;
  }
  for (int i = 1; i <= n; ++i) {
    in[p[i]]++;
  }
  for (int i = 1; i <= n; ++i) {
    if (!in[i]) {
      q.push(i);
      col[i] = -1;
    }
  }
  while (q.size()) {
    int u = q.front();
    q.pop();
    --in[p[u]];
    if (!in[p[u]]) {
      q.push(p[u]);
      col[p[u]] = -1;
    }
  }
  for (int i = 1; i <= n; ++i) {
    if (col[i]) {
      continue;
    }
    col[i] = ++cnt;
    e[cnt].push_back(c[i]);
    dfs(p[i], i);
  }
}
int work(const vector<int>& a) {
  int n = a.size();
  for (int i = 1; i <= n; ++i) {
    if (n % i) continue;
    for (int be = 0; be < i; ++be) {
      bool ok = 1;
      for (int j = be; j < n; j += i) {
        if (a[j] != a[be]) {
          ok = 0;
          break;
        }
      }
      if (ok) return i;
    }
  }
  return n;
}
void solve() {
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> p[i];
  }
  for (int i = 1; i <= n; ++i) {
    cin >> c[i];
  }
  topo();
  mi = n;
  for (int i = 1; i <= cnt; ++i) {
    mi = min(mi, work(e[i]));
  }
  cout << mi << endl;
}
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int T = 1;
  cin >> T;
  while (T--) {
    solve();
  }
  return 0;
}
