#include <bits/stdc++.h>
using namespace std;
inline void Input_Output() {}
const double eps = 0.000001;
const long double pi = acos(-1);
const int maxn = 1e7 + 9;
const int mod = 1e9 + 7;
const long long MOD = 1e18 + 9;
const long long INF = 1e18 + 123;
const int inf = 2e9 + 11;
const int mxn = 1e6 + 9;
const int N = 2e5 + 123;
const int K = 20;
const int pri = 997;
const int Magic = 2101;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
int n, m, k;
int p[N];
int c[N];
bool good;
vector<int> g[N];
inline void solve() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", p + i);
  }
  for (int i = 1; i <= n; i++) {
    scanf("%d", c + i);
  }
  int ans = n;
  for (int i = 1; i <= n; ++i) {
    if (p[i] == -1) continue;
    vector<int> cyc;
    for (int j = i; p[j] != -1;) {
      cyc.push_back(c[j]);
      int nj = p[j];
      p[j] = -1;
      j = nj;
    }
    for (auto k : g[(int)(cyc.size())]) {
      for (int st = 0; st < k; ++st) {
        good = 1;
        for (int v = st; v < (int)(cyc.size()); v += k) {
          if (cyc[v] != cyc[st]) {
            good = 0;
            break;
          }
        }
        if (good) ans = min(ans, k);
      }
    }
  }
  printf("%d\n", ans);
}
int main() {
  for (int i = 1; i < N; ++i)
    for (int j = i; j < N; j += i) g[j].push_back(i);
  int tt = 1;
  scanf("%d", &tt);
  while (tt--) solve();
  return 0;
}
