#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &x) {
  T f = 1, ch = getchar();
  x = 0;
  while (!isdigit(ch)) {
    f = ch == '-' ? -1 : 1, ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + ch - 48, ch = getchar();
  }
  x *= f;
}
template <typename T>
void print(T x) {
  if (x < 0) {
    putchar('-'), x = -x;
  }
  if (x > 9) {
    print(x / 10);
  }
  putchar(x % 10 + '0');
}
template <typename T, typename... Args>
inline void read(T &t, Args &...args) {
  read(t);
  read(args...);
}
const int N = 2e5 + 9;
int p[N], c[N], vis[N], huan[N], ans[N], T, n;
bool check(int len, int k) {
  bool flag = false;
  for (int i = 0; i < k; ++i) {
    bool tot = true;
    for (int cur = i; cur < len; cur += k) {
      if (c[huan[cur]] != c[huan[(cur + k) % len]]) {
        tot = false;
        break;
      }
    }
    if (tot) {
      flag = true;
      break;
    }
  }
  return flag;
}
int main() {
  read(T);
  while (T--) {
    read(n);
    for (int i = 1; i <= n; ++i) {
      read(p[i]);
      vis[i] = 0;
      ans[i] = 0;
    }
    for (int i = 1; i <= n; ++i) {
      read(c[i]);
    }
    for (int i = 1; i <= n; ++i) {
      if (!vis[i]) {
        int now = i, len = 0;
        while (!vis[now]) {
          vis[now] = 1;
          huan[len++] = now;
          now = p[now];
        }
        for (int j = 1; j * j <= len; ++j) {
          if (len % j != 0) continue;
          if (check(len, j)) ans[j] = 1;
          if (check(len, len / j)) ans[len / j] = 1;
        }
      }
    }
    for (int i = 1; i <= n; ++i) {
      if (ans[i]) {
        printf("%d\n", i);
        break;
      }
    }
  }
  return 0;
}
