#include <bits/stdc++.h>
using namespace std;
const int inf = 1 << 30;
const long long linf = 1LL << 62;
const int MAX = 510000;
long long dy[8] = {0, 1, 0, -1, 1, -1, 1, -1};
long long dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
const double pi = acos(-1);
const double eps = 1e-7;
template <typename T1, typename T2>
inline bool chmin(T1 &a, T2 b) {
  if (a > b) {
    a = b;
    return true;
  } else
    return false;
}
template <typename T1, typename T2>
inline bool chmax(T1 &a, T2 b) {
  if (a < b) {
    a = b;
    return true;
  } else
    return false;
}
template <typename T1, typename T2>
inline void print2(T1 a, T2 b) {
  cout << a << " " << b << endl;
}
template <typename T1, typename T2, typename T3>
inline void print3(T1 a, T2 b, T3 c) {
  cout << a << " " << b << " " << c << endl;
}
const int mod = 1e9 + 7;
void solve() {
  long long n;
  cin >> n;
  vector<long long> p(n), c(n);
  for (long long i = 0; i < (n); i++) cin >> p[i], p[i]--;
  for (long long i = 0; i < (n); i++) cin >> c[i];
  vector<bool> visit(n, false);
  long long ans = n;
  for (long long i = 0; i < (n); i++) {
    if (visit[i]) continue;
    long long now = i;
    vector<long long> cycle;
    while (!visit[now]) {
      cycle.push_back(now);
      visit[now] = true;
      now = p[now];
    }
    long long m = cycle.size();
    chmin(ans, m);
    for (long long j = (1); j < (m); j++) {
      if (m % j) continue;
      for (long long k = 0; k < (j); k++) {
        bool ok = true;
        for (long long l = k; l + j < m; l += j) {
          if (c[cycle[l]] != c[cycle[l + j]]) {
            ok = false;
            break;
          }
        }
        if (ok) chmin(ans, j);
      }
    }
  }
  cout << ans << endl;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
}
