#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long INF = (long long)1000000007 * 1000000007;
const long double eps = 1e-8;
const long double pi = acos(-1.0);
int q;
template <typename T>
vector<T> divisor_list(T x) {
  vector<T> res;
  for (T i = 1; i * i <= x; i++) {
    if (x % i == 0) {
      res.push_back(i);
      if (i * i != x) res.push_back(x / i);
    }
  }
  sort(res.begin(), res.end());
  return res;
}
int calc(vector<int> &v, vector<int> &c) {
  int m = v.size();
  vector<int> d = divisor_list(m);
  for (int g : d) {
    for (int r = 0; r < g; r++) {
      bool ok = true;
      for (int k = 0; k < m / g - 1; k++) {
        if (c[v[k * g + r]] != c[v[(k + 1) * g + r]]) {
          ok = false;
          break;
        }
      }
      if (ok) return g;
    }
  }
  return m;
}
void solve() {
  cin >> q;
  for (int _ = 0; _ < q; _++) {
    int n;
    cin >> n;
    vector<int> p(n), c(n);
    vector<int> nex(n);
    for (int i = 0; i < n; i++) {
      cin >> p[i];
      p[i] -= 1;
    }
    for (int i = 0; i < n; i++) {
      cin >> c[i];
      c[i] -= 1;
    }
    vector<bool> visited(n);
    int ans = mod;
    for (int i = 0; i < n; i++) {
      if (visited[i]) continue;
      visited[i] = true;
      vector<int> v = {i};
      while (!visited[p[v.back()]]) {
        v.push_back(p[v.back()]);
        visited[v.back()] = true;
      }
      ans = min(ans, calc(v, c));
    }
    printf("%d\n", ans);
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout << fixed << setprecision(50);
  solve();
}
