#include <bits/stdc++.h>
using namespace std;
int a[200005], b[200005], cnt;
set<int> s;
int tmp[200005];
void dfs(int x) {
  if (s.find(x) != s.end()) {
    return;
  }
  tmp[++cnt] = x;
  s.insert(x);
  dfs(a[x]);
}
int solve() {
  int an = cnt;
  for (int i = 1; i * i <= cnt; i++) {
    if (cnt % i) continue;
    for (int j = 1; j <= i; j++) {
      int k;
      for (k = j + i; k <= cnt; k += i) {
        if (b[tmp[k]] != b[tmp[k - i]]) break;
      }
      if (k > cnt) an = min(an, i);
    }
    int i2 = cnt / i;
    for (int j = 1; j <= i2; j++) {
      int k;
      for (k = j + i2; k <= cnt; k += i2) {
        if (b[tmp[k]] != b[tmp[k - i2]]) break;
      }
      if (k > cnt) an = min(an, i2);
    }
  }
  return an;
}
int main() {
  int t, n;
  cin >> t;
  int ma = n;
  while (t--) {
    s.clear();
    cin >> n;
    ma = n;
    for (int i = 1; i <= n; i++) scanf("%d", a + i);
    for (int i = 1; i <= n; i++) scanf("%d", b + i);
    for (int i = 1; i <= n; i++) {
      if (s.find(i) == s.end()) {
        cnt = 0;
        dfs(i);
        ma = min(solve(), ma);
      }
    }
    printf("%d\n", ma);
  }
}
