#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
int p[N], c[N];
bool vis[N];
vector<int> divs(int n) {
  vector<int> ans;
  for (int i = 1; i * i <= n; i++) {
    if (n % i) continue;
    ans.push_back(i);
    if (i * i != n) ans.push_back(n / i);
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> p[i];
    for (int i = 1; i <= n; i++) cin >> c[i];
    int ans = N;
    for (int i = 1; i <= n; i++) {
      if (vis[i]) continue;
      int cur = i;
      vector<int> vp;
      while (true) {
        vp.push_back(c[cur]);
        vis[cur] = 1;
        cur = p[cur];
        if (cur == i) break;
      }
      int k = vp.size();
      for (int p : divs(k)) {
        for (int i = 0; i < p; i++) {
          bool good = true;
          for (int j = i; j < k; j += p) {
            if (vp[j] != vp[i]) {
              good = false;
              break;
            }
          }
          if (good) ans = min(ans, p);
        }
      }
    }
    cout << ans << endl;
    fill(vis, vis + n + 1, 0);
  }
}
