#include <bits/stdc++.h>
using namespace std;
int t, n;
const int maxn = 200005;
int a[maxn], c[maxn], v[maxn];
bool ok(vector<int> o, int k) {
  int len = o.size();
  int t, p;
  bool flag = true;
  for (int i = 0; i < k; i++) {
    flag = true;
    t = c[o[i]];
    p = (i + k) % len;
    while (p != i) {
      if (c[o[p]] != t) {
        flag = false;
        break;
      }
      p = (p + k) % len;
    }
    if (flag) return true;
  }
  return false;
}
int main() {
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    int ans = 1e9;
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    for (int i = 1; i <= n; i++) scanf("%d", &c[i]);
    for (int i = 1; i <= n; i++) v[i] = 0;
    for (int i = 1; i <= n; i++)
      if (v[i] == 0) {
        vector<int> quan;
        int temp = i;
        quan.push_back(temp);
        v[i] = 1;
        temp = a[i];
        while (temp != i) {
          quan.push_back(temp);
          v[temp] = 1;
          temp = a[temp];
        }
        int len = quan.size();
        for (int k = 1; k * k <= len; k++) {
          if (len % k == 0) {
            if (ok(quan, k)) ans = min(ans, k);
            if (ok(quan, len / k)) ans = min(ans, len / k);
          }
        }
      }
    printf("%d\n", ans);
  }
  return 0;
}
