#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 2e5 + 42;
int p[N], c[N];
char u[N];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t = 0;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
      u[i] = 0;
      cin >> p[i];
      p[i]--;
    }
    for (int i = 0; i < n; i++) cin >> c[i];
    int ans = n + 1;
    for (int i = 0; i < n; i++) {
      if (u[i]) continue;
      vector<int> cyc;
      int cv = i;
      while (!u[cv]) {
        u[cv] = true;
        cyc.push_back(cv);
        cv = p[cv];
      }
      int len = cyc.size();
      for (int step = 1; step <= len; step++) {
        if (len % step) continue;
        for (int st = 0; st < step; st++) {
          char ok = true;
          for (int cp = st; cp + step < len; cp += step)
            ok &= (c[cyc[cp]] == c[cyc[cp + step]]);
          if (ok) ans = min(ans, step);
        }
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
