#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-10;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const int maxn = 2e5 + 5;
int T, n, tot, flag;
int p[maxn], c[maxn], vis[maxn];
vector<int> g[maxn];
void dfs1(int u) {
  if (vis[u]) return;
  vis[u] = 1;
  g[tot].push_back(u);
  dfs1(p[u]);
}
void dfs2(int p, int step, int m, int cc, int id) {
  if (vis[p]) return;
  vis[p] = 1;
  if (c[g[id][p]] != cc) flag = 0;
  int nxt = (p + step) % m;
  dfs2(nxt, step, m, cc, id);
}
int main(void) {
  scanf("%d", &T);
  while (T--) {
    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]);
    }
    tot = 0;
    for (int i = 1; i <= n; i++) vis[i] = 0, g[i].clear();
    for (int i = 1; i <= n; i++) {
      if (!vis[i]) {
        ++tot;
        dfs1(i);
      }
    }
    int ans = INF;
    for (int i = 1; i <= tot; i++) {
      int sz = g[i].size();
      int rnd = INF;
      for (int j = 1; j * j <= sz; j++) {
        if (sz % j != 0) continue;
        for (int k = 0; k < sz; k++) vis[k] = 0;
        for (int k = 0; k < sz; k++) {
          if (!vis[k]) {
            flag = 1;
            dfs2(k, j, sz, c[g[i][k]], i);
            if (flag) rnd = min(rnd, j);
          }
        }
        int tj = sz / j;
        if (tj != j) {
          for (int k = 0; k < sz; k++) vis[k] = 0;
          for (int k = 0; k < sz; k++) {
            if (!vis[k]) {
              flag = 1;
              dfs2(k, tj, sz, c[g[i][k]], i);
              if (flag) rnd = min(rnd, tj);
            }
          }
        }
      }
      ans = min(ans, rnd);
    }
    printf("%d\n", ans);
  }
  return 0;
}
