#include <bits/stdc++.h>
using namespace std;
template <class T = int>
using V = vector<T>;
template <class T = int>
using VV = V<V<T>>;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pdd = pair<ld, ld>;
vector<long long> divisor(long long n) {
  vector<long long> ret;
  for (long long i = 1; i * i <= n; i++) {
    if (n % i == 0) {
      ret.push_back(i);
      if (i * i != n) ret.push_back(n / i);
    }
  }
  sort(ret.begin(), ret.end());
  return ret;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    V<int> p(n), c(n);
    for (int i = 0; i < (n); i++) cin >> p[i], p[i]--;
    for (int i = 0; i < (n); i++) cin >> c[i];
    V<int> seen(n);
    int ans = 1e9;
    for (int i = 0; i < (n); i++) {
      if (seen[i]) continue;
      V<int> e;
      e.push_back(i);
      int id = i;
      seen[i] = 1;
      while (1) {
        int x = p[id];
        if (x == i) break;
        e.push_back(x);
        seen[x] = 1;
        id = x;
      }
      int sz = e.size();
      auto ret = divisor(sz);
      for (int x : ret) {
        for (int j = 0; j < (x); j++) {
          int idx = j;
          int col = c[e[idx]];
          bool f = true;
          for (int k = 0; k < (sz / x - 1); k++) {
            idx += x;
            if (col != c[e[idx]]) {
              f = false;
              break;
            }
          }
          if (f) ans = min(ans, x);
        }
      }
    }
    cout << ans << endl;
  }
}
