#include <bits/stdc++.h>
using namespace std;
template <class c>
struct rge {
  c b, e;
};
template <class c>
rge<c> range(c i, c j) {
  return rge<c>{i, j};
}
template <class c>
auto dud(c* x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct debug {
  template <class c>
  debug& operator<<(const c&) {
    return *this;
  }
};
void solve();
const int N = 2e5 + 10;
const long long INF = 1e18;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
}
void solve() {
  int n;
  cin >> n;
  vector<int> a(n + 1), c(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 1; i <= n; i++) {
    cin >> c[i];
  }
  long long ans = INF;
  vector<bool> visited(n + 1);
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    vector<int> cycle;
    int index = i;
    while (!visited[index]) {
      cycle.push_back(index);
      visited[index] = 1;
      index = a[index];
    }
    for (int j = 1; j <= cycle.size(); j++) {
      if (cycle.size() % j != 0) continue;
      for (int pos = 0; pos < j; pos++) {
        bool flag = 1;
        for (int s = pos; s + j < cycle.size(); s += j) {
          if (c[cycle[s]] != c[cycle[s + j]]) flag = 0;
        }
        if (flag) ans = min(ans, (long long)j);
      }
    }
  }
  cout << ans << '\n';
}
