#include <bits/stdc++.h>
#pragma GCC optimize("Ofast", "unroll-loops")
using namespace std;
vector<long long> divisor(long long k) {
  vector<long long> d;
  for (long long i = 1; i * i <= k; ++i) {
    if (k % i == 0) {
      d.push_back(i);
      if (i * i != k) d.push_back(k / i);
    }
  }
  sort(d.begin(), d.end());
  return d;
}
int calc(vector<int>& lis) {
  auto hoge = divisor(lis.size());
  for (auto step : hoge) {
    for (int st = 0; st < step; ++st) {
      map<int, int> appered;
      int now = st;
      while (1) {
        appered[now] = 1;
        if (lis[now] != lis[(now + step) % lis.size()]) goto FIN;
        now = (now + step) % lis.size();
        if (appered[now]) return step;
      }
    FIN:;
    }
  }
}
void solve() {
  int n;
  cin >> n;
  vector<int> p(n);
  for (int i = 0; i < n; ++i) {
    cin >> p[i];
    --p[i];
  }
  vector<int> c(n);
  for (int i = 0; i < n; ++i) cin >> c[i];
  map<int, int> appered;
  int res = 2000000;
  for (int i = 0; i < n; ++i) {
    if (appered[i]) continue;
    vector<int> list;
    int now = i;
    while (!appered[now]) {
      appered[now] = 1;
      list.push_back(c[now]);
      now = p[now];
    }
    res = min(res, calc(list));
  }
  cout << res << endl;
}
int main() {
  int T;
  cin >> T;
  while (T--) solve();
  return 0;
}
