#include <bits/stdc++.h>
const int MAXN = 2e5 + 10;
using namespace std;
int T, N, cmp;
int p[MAXN], c[MAXN];
vector<int> comp[MAXN];
bool vis[MAXN];
void dfs(int x) {
  vis[x] = true;
  comp[cmp].push_back(c[x]);
  if (!vis[p[x]]) dfs(p[x]);
}
int min_ans(int idx_comp) {
  int n_comp = (int)(comp[idx_comp].size());
  vector<int> div;
  for (long long i = 1; i * i <= 1LL * n_comp; i++)
    if (n_comp % i == 0) {
      div.push_back((int)i);
      if (i * i != 1LL * n_comp) div.push_back((int)(n_comp / i));
    }
  sort(div.begin(), div.end());
  for (int d : div)
    for (int i = 0; i < d; i++) {
      int g = (i + d) % n_comp;
      bool found = true;
      while (g != i) {
        if (comp[idx_comp][g] != comp[idx_comp][i]) found = false;
        g = (g + d) % n_comp;
      }
      if (found) return d;
    }
}
inline void init() {
  cmp = 0;
  for (int i = 1; i < N + 1; i++) {
    vis[i] = false;
    comp[i].clear();
  }
}
int main() {
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &N);
    init();
    for (int i = 1; i < N + 1; i++) scanf("%d", &p[i]);
    for (int i = 1; i < N + 1; i++) scanf("%d", &c[i]);
    for (int i = 1; i < N + 1; i++)
      if (!vis[i]) {
        cmp++;
        dfs(i);
      }
    int mn = N;
    for (int i = 1; i < cmp + 1; i++) mn = min(mn, min_ans(i));
    printf("%d\n", mn);
  }
}
