#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
int solve(int n, vector<int> &p, vector<int> &c) {
  int res = INT_MAX;
  vector<bool> used(n, false);
  for (__typeof(n) i = (0) - ((0) > (n)); i != (n) - ((0) > (n));
       i += 1 - (((0) > (n)) << 1)) {
    if (used[i]) continue;
    vector<int> cycle;
    for (int j = i; not used[j]; j = p[j]) {
      cycle.push_back(j);
      used[j] = true;
    }
    for (int step = 1; step <= ((int)cycle.size()); step++) {
      if (((int)cycle.size()) % step) continue;
      for (__typeof(step) start = (0) - ((0) > (step));
           start != (step) - ((0) > (step));
           start += 1 - (((0) > (step)) << 1)) {
        bool eq = true;
        for (int pos = start; pos < ((int)cycle.size()); pos += step) {
          if (c[cycle[pos]] != c[cycle[start]]) {
            eq = false;
            break;
          }
        }
        if (eq) {
          res = min(res, step);
          break;
        }
      }
    }
  }
  return res;
}
int32_t main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<int> p(n), c(n);
    for (int &i : p) {
      cin >> i;
      i--;
    }
    for (int &i : c) cin >> i;
    cout << solve(n, p, c) << "\n";
  }
  return 0;
}
