#include <bits/stdc++.h>
using namespace std;
const int N = 2 * 100 * 1000 + 20, inf = 1e9;
int n, a[N], ans = inf, c[N];
bool mark[N];
vector<int> vec;
void dfs(int v) {
  vec.push_back(v);
  mark[v] = true;
  if (!mark[a[v]]) dfs(a[v]);
}
bool ok(int k, int j) {
  for (int i = j + k; i < vec.size(); i += j)
    if (c[vec[i]] != c[vec[i - j]]) return false;
  return true;
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> n;
    for (int i = 0; i < n; i++) {
      cin >> a[i];
      a[i]--;
    }
    for (int i = 0; i < n; i++) cin >> c[i];
    for (int i = 0; i < n; i++)
      if (!mark[i]) {
        dfs(i);
        for (int j = 1; j <= vec.size(); j++)
          if (vec.size() % j == 0)
            for (int k = 0; k < j; k++)
              if (ok(k, j)) ans = min(ans, j);
        vec.clear();
      }
    cout << ans << "\n";
    fill(mark, mark + n, false);
    ans = inf;
  }
  return 0;
}
