#include <bits/stdc++.h>
using namespace std;
void testcase() {
  int n;
  cin >> n;
  vector<int> p(n);
  for (auto &x : p) {
    cin >> x;
    x -= 1;
  }
  vector<int> c(n);
  for (auto &x : c) cin >> x;
  int smallest_k = 1e9;
  vector<int> visited(n, false);
  for (int i = 0; i < n; ++i) {
    if (visited[i]) continue;
    visited[i] = true;
    int orbit = 1;
    vector<int> orbit_colors = {c[i]};
    int x = p[i];
    while (i != x) {
      visited[x] = true;
      orbit_colors.push_back(c[x]);
      x = p[x];
      ++orbit;
    }
    for (int step = 1; step <= orbit; ++step) {
      if (orbit % step != 0) continue;
      for (int start = 0; start < step; ++start) {
        bool good = true;
        for (int i = start; i < orbit; i += step) {
          if (orbit_colors[i] != orbit_colors[(i + step) % orbit]) {
            good = false;
            break;
          }
        }
        if (good) {
          smallest_k = min(smallest_k, step);
        }
      }
    }
  }
  cout << smallest_k << endl;
}
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    testcase();
  }
  return 0;
}
