#include <bits/stdc++.h>
using namespace std;
long long mod = 1000000007;
vector<int> divisors(int n) {
  vector<int> div;
  for (int i = 1; i <= sqrt(n); i++) {
    if (n % i == 0) {
      if (n / i == i) {
        div.push_back(i);
      } else {
        div.push_back(i);
        div.push_back(n / i);
      }
    }
  }
  return div;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<int> p(n), c(n);
    for (int i = 0; i < n; i++) {
      cin >> p[i];
      p[i]--;
    }
    int col;
    for (int i = 0; i < n; i++) {
      cin >> col;
      c[p[i]] = col;
    }
    vector<vector<int>> cycles;
    vector<int> cycle;
    vector<bool> visit(n, false);
    for (int i = 0; i < n; i++) {
      int s = p[i];
      if (visit[s]) {
        continue;
      }
      cycle.clear();
      while (!visit[s]) {
        cycle.push_back(s);
        visit[s] = true;
        s = p[s];
      }
      cycles.push_back(cycle);
    }
    int _min = INT_MAX;
    for (auto cycle : cycles) {
      int len = cycle.size();
      vector<int> fact = divisors(len);
      for (auto val : fact) {
        for (int i = 0; i < val; i++) {
          int elem = cycle[i];
          int col = c[elem];
          bool ok = true;
          int ind = i;
          while (ind + val < len) {
            ind += val;
            elem = cycle[ind];
            if (col != c[elem]) {
              ok = false;
              break;
            }
          }
          if (ok) {
            _min = min(_min, val);
            break;
          }
        }
      }
    }
    cout << _min << endl;
  };
  return 0;
}
