#include <bits/stdc++.h>
using namespace std;
void Solve() {
  int n = 0;
  cin >> n;
  vector<int> p(n);
  vector<int> c(n);
  for (int i = 0; i < n; i++) {
    cin >> p[i];
    p[i]--;
  }
  for (int i = 0; i < n; i++) {
    cin >> c[i];
  }
  vector<bool> visited(n, false);
  auto findCircle = [&](int u) {
    auto ci = make_shared<vector<int>>();
    int v = u;
    do {
      ci->push_back(v);
      visited[v] = true;
      v = p[v];
    } while (v != u);
    return ci;
  };
  auto checkKValid = [&](shared_ptr<vector<int>> ci, int k) {
    int c_len = (int)ci->size();
    vector<bool> c_visited(ci->size());
    for (int u = 0; u < c_len; u++) {
      if (c_visited[u]) {
        continue;
      }
      bool valid = true;
      for (int step = k; step < c_len; step += k) {
        int v = (u + step) % c_len;
        if (c[(*ci)[u]] != c[(*ci)[v]]) {
          valid = false;
        }
        c_visited[v] = true;
      }
      if (valid) {
        return true;
      }
    }
    return false;
  };
  int ans = n;
  for (int u = 0; u < n; u++) {
    if (visited[u]) {
      continue;
    }
    auto ci = findCircle(u);
    int c_len = (int)ci->size();
    for (int k = 1; k * k <= c_len; k++) {
      if (c_len % k == 0) {
        if (checkKValid(ci, k)) {
          ans = min(ans, k);
        }
        if (checkKValid(ci, c_len / k)) {
          ans = min(ans, c_len / k);
        }
      }
    }
  }
  cout << ans << endl;
}
int main(int argc, char** argv) {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  int t = 1;
  cin >> t;
  while (t--) {
    Solve();
  }
  return 0;
}
