#include <bits/stdc++.h>
using namespace std;
int T, n, p[200005], ans, col[200005];
vector<int> fac[200005], V;
bool vis[200005];
int getAns() {
  for (auto &f : fac[V.size()]) {
    for (int i = 0; i < f; i++) {
      bool flag = true;
      for (int j = i; j < V.size() && flag; j += f)
        if (V[j] != V[i]) flag = false;
      if (flag) return f;
    }
  }
  return -1;
}
int main() {
  scanf("%d", &T);
  for (int i = 1; i <= 200000; i++)
    for (int j = i; j <= 200000; j += i) fac[j].push_back(i);
  while (T--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d", &p[i]), vis[i] = false;
    for (int i = 1; i <= n; i++) scanf("%d", &col[i]);
    ans = 1E9;
    for (int i = 1; i <= n; i++)
      if (!vis[i]) {
        int j = i;
        V.clear();
        while (!vis[j]) {
          vis[j] = true;
          V.push_back(col[j]);
          j = p[j];
        }
        ans = min(ans, getAns());
      }
    printf("%d\n", ans);
  }
  return 0;
}
