#include <bits/stdc++.h>
using namespace std;
const int maxn = 211111;
long long n, p[maxn], c[maxn], res;
bool vis[maxn];
vector<long long> vv;
void brd(long long x) {
  int i = x;
  vv.clear();
  while (vv.empty() || i != x) {
    vv.push_back(i);
    vis[i] = true;
    i = p[i] - 1;
  }
}
bool check(long long st, long long num) {
  long long stan = c[vv[st]], nw = 0;
  for (int i = st; nw == 0 || i != st; nw++, i = (i + num) % vv.size())
    if (c[vv[i]] != stan) return false;
  return true;
}
void gmin() {
  if (check(0, 1)) {
    res = 1;
    return;
  }
  for (int i = 2; i <= vv.size(); i++) {
    if (vv.size() % i != 0) continue;
    for (int j = 0; j < i; j++) {
      if (check(j, i)) {
        res = min(res, (long long)i);
        return;
      }
    }
  }
  return;
}
int main() {
  long long T;
  scanf("%lld", &T);
  for (int tc = 0; tc < T; tc++) {
    scanf("%lld", &n);
    for (int i = 0; i < n; i++) scanf("%lld", &p[i]);
    for (int i = 0; i < n; i++) scanf("%lld", &c[i]);
    res = 1000000000000000000;
    for (int i = 0; i < n; i++) vis[i] = false;
    for (int i = 0; i < n; i++) {
      if (!vis[i]) {
        brd(i);
        gmin();
      }
    }
    printf("%lld\n", res);
  }
  return 0;
}
