#include <bits/stdc++.h>
using namespace std;
int t, n, p[200005], c[200005], id, kk, ans, currc;
vector<int> v[200005];
bool vis[200005], ok;
void loop(int dd) {
  if (vis[dd]) return;
  v[id].push_back(dd);
  vis[dd] = true;
  loop(p[dd]);
  return;
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> t;
  while (t--) {
    cin >> n;
    ans = n;
    for (int i = 0; i < n; i++) cin >> p[i + 1];
    for (int i = 0; i < n; i++) cin >> c[i + 1];
    for (int i = 1; i <= n; i++) vis[i] = 0;
    int dx = 0;
    id = 0;
    while (dx < n) {
      dx++;
      if (vis[p[dx]]) continue;
      loop(p[dx]);
      id++;
    }
    for (int i = 0; i < id; i++) {
      kk = 0;
      int q = v[i].size();
      ans = min(ans, q);
      while (kk < v[i].size()) {
        kk++;
        if (q % kk != 0) continue;
        for (int j = 0; j < kk; j++) {
          currc = c[v[i][j]];
          ok = 1;
          for (int k = j; k < v[i].size() && ok; k += kk) {
            if (c[v[i][k]] != currc) ok = 0;
          }
          if (ok) ans = min(ans, kk);
        }
      }
    }
    for (int i = 0; i < id; i++) {
      while (!v[i].empty()) v[i].pop_back();
    }
    cout << ans << endl;
  }
}
