#include <bits/stdc++.h>
using namespace std;
long long t, n, p[200100], c[200100], ans = 100100;
bool hamin[200100];
vector<vector<long long> > cycle;
bool same_color(long long ind, long long start, long long dist) {
  long long asdf = (start + dist) % cycle[ind].size();
  while (asdf != start) {
    if (c[cycle[ind][start]] != c[cycle[ind][asdf]]) return false;
    asdf = (asdf + dist) % cycle[ind].size();
  }
  return true;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> t;
  while (t--) {
    ans = 100000000;
    cycle.clear();
    cin >> n;
    for (int i = 1; i <= n; i++) hamin[i] = false;
    for (int i = 1; i <= n; i++) cin >> p[i];
    for (int i = 1; i <= n; i++) cin >> c[i];
    for (int i = 1; i <= n; i++) {
      if (hamin[i]) continue;
      long long start = i;
      vector<long long> fuck;
      fuck.push_back(start);
      hamin[start] = true;
      while (p[start] != fuck[0]) {
        start = p[start];
        fuck.push_back(start);
        hamin[start] = true;
      }
      cycle.push_back(fuck);
    }
    for (long long i = 0; i < cycle.size(); i++) {
      for (long long j = 1; j <= cycle[i].size(); j++) {
        if (cycle[i].size() % j) continue;
        for (long long z = 0; z < j; z++)
          if (same_color(i, z, j)) ans = min(ans, j);
      }
    }
    cout << ans << "\n";
  }
}
