#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int T;
int n;
int p[maxn], c[maxn];
bool used[maxn];
void read_input() {
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> p[i];
    --p[i];
  }
  for (int i = 0; i < n; ++i) cin >> c[i];
}
void solve() {
  fill(used, used + n, false);
  int ans = 1e9 + 9;
  for (int s = 0; s < n; ++s) {
    if (used[s]) continue;
    vector<int> cycle;
    int u = s;
    while (!used[u]) {
      cycle.push_back(u);
      used[u] = true;
      u = p[u];
    }
    int len = cycle.size();
    for (int k = 1; k <= len; ++k) {
      if (len % k != 0) continue;
      for (int i = 0; i < k; ++i) {
        bool ok = true;
        for (int j = i; j < len; j += k)
          if (c[cycle[i]] != c[cycle[j]]) {
            ok = false;
            break;
          }
        if (ok) {
          ans = min(ans, k);
          break;
        }
      }
    }
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> T;
  while (T--) {
    read_input();
    solve();
  }
}
