#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cout.tie(nullptr);
  cin.tie(nullptr);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<int> p(n), c(n), vis(n, 0);
    for (int i = 0; i < n; ++i) {
      cin >> p[i];
      p[i]--;
    }
    for (int i = 0; i < n; ++i) cin >> c[i];
    int ans = INT_MAX;
    for (int i = 0; i < n; ++i) {
      if (vis[i]) continue;
      vector<int> cy;
      int j = i;
      while (!vis[j]) {
        cy.push_back(c[j]);
        vis[j] = 1;
        j = p[j];
      }
      int s = cy.size();
      for (int d = 1; d <= s; ++d) {
        if (s % d) continue;
        vector<bool> vis2(s, 0);
        for (int l = 0; l < s; ++l) {
          if (vis2[l]) continue;
          bool same = 1;
          int nw = l;
          while (!vis2[nw]) {
            if (cy[nw] != cy[(nw + d) % s]) same = 0;
            vis2[nw] = 1;
            nw = (nw + d) % s;
          }
          if (same) ans = min(ans, d);
        }
      }
    }
    cout << ans << '\n';
  }
}
