#include <bits/stdc++.h>
using namespace std;
inline bool Read(int &a) { return scanf("%d", &a) != EOF; }
inline bool Read(int &a, int &b) { return scanf("%d%d", &a, &b) != EOF; }
inline bool Read(int &a, int &b, int &c) {
  return scanf("%d%d%d", &a, &b, &c) != EOF;
}
inline bool Read(int &a, int &b, int &c, int &d) {
  return scanf("%d%d%d%d", &a, &b, &c, &d) != EOF;
}
const int INF = 0x3f3f3f3f;
struct Edge {
  int u;
  int v;
  int d;
  Edge() {}
  Edge(int u, int v, int d) : u(u), v(v), d(d) {}
  bool operator<(const Edge &x) const { return d < x.d; }
};
struct HeadNode {
  int d;
  int u;
  HeadNode() {}
  HeadNode(int d, int u) : d(d), u(u) {}
  bool operator<(const HeadNode &x) const { return d > x.d; }
};
const int maxn = 2e5 + 10;
int p[maxn];
int c[maxn];
int cir[maxn];
int Process() {
  int T;
  Read(T);
  for (int _i = 0; _i < T; _i++) {
    int n;
    Read(n);
    for (int i = 1; i <= n; i++) Read(p[i]);
    for (int i = 1; i <= n; i++) Read(c[i]);
    int minv = INF;
    for (int i = 1; i <= n; i++) {
      if (p[i] == -1) continue;
      int cnt = 0;
      int x = i;
      do {
        cir[cnt++] = x;
        int y = p[x];
        p[x] = -1;
        x = y;
      } while (x != i);
      for (int k = 1; k < minv && k <= cnt; k++) {
        if (cnt % k != 0) continue;
        bool ok = true;
        for (int begin_idx = 0; begin_idx < k; begin_idx++) {
          int x = begin_idx;
          ok = true;
          do {
            if (c[cir[x]] != c[cir[begin_idx]]) {
              ok = false;
              break;
            }
            x = (x + k) % cnt;
          } while (x != begin_idx);
          if (ok) break;
        }
        if (ok) {
          minv = min(minv, k);
        }
      }
    }
    printf("%d\n", minv);
  }
  return 0;
}
int main() {
  std::ios::sync_with_stdio(false);
  return Process();
}
