#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-6, pi = acos(-1.0);
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int n, p[maxn], c[maxn];
int vis[maxn];
vector<int> path[maxn];
void dfs(int fa, int x) {
  if (vis[x]) return;
  vis[x] = 1;
  path[fa].push_back(x);
  dfs(fa, p[x]);
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
      scanf("%d", &p[i]);
      vis[i] = 0;
      path[i].clear();
    }
    for (int i = 1; i <= n; ++i) {
      scanf("%d", &c[i]);
    }
    int ans = inf;
    for (int i = 1; i <= n; ++i) {
      if (vis[i]) continue;
      dfs(i, i);
    }
    for (int i = 1; i <= n; ++i) {
      int tot = path[i].size();
      for (int j = 1; j <= tot; ++j) {
        if (tot % j != 0) continue;
        for (int k = 0; k < j; ++k) {
          int ok = 1, t = c[path[i][k]];
          for (int z = k; z < tot; z += j) {
            if (t == c[path[i][z]]) continue;
            ok = 0;
            break;
          }
          if (ok) ans = min(ans, j);
        }
      }
    }
    printf("%d\n", ans);
  }
}
