#include <bits/stdc++.h>
using namespace std;
template <typename T>
void show(T *a, int size) {
  int i;
  cout << endl << "The array is ";
  for (long long i = 0; i < size; ++i) {
    cout << a[i] << " ";
  }
  cout << endl;
}
template <typename T>
void show_vector(vector<T> v) {
  cout << endl << "The vector is ";
  int i;
  for (long long i = 0; i < v.size(); ++i) {
    cout << v[i] << " ";
  }
  cout << endl;
}
long long int p[200005], c[200005], t, n, visited[200005];
vector<long long> v;
vector<long long> factorization(long long int x) {
  vector<long long> rv;
  for (long long int i = 1; i <= x; i++) {
    if (x % i == 0) {
      rv.push_back(i);
    }
  }
  return rv;
}
bool possible(long long int x) {
  for (long long i = 0; i < x; ++i) {
    long long int flag = 0;
    for (long long int j = i; j < v.size(); j += x) {
      if (c[p[v[j]]] != c[p[v[i]]]) {
        flag = 1;
        break;
      }
    }
    if (flag == 0) return true;
  }
  return false;
}
long long int func2() {
  long long int len = v.size();
  vector<long long> factors = factorization(len);
  for (long long int factor : factors) {
    if (possible(factor)) {
      return factor;
    }
  }
  return len;
}
long long int dfs(long long int par, long long int child) {
  visited[child] = true;
  v.push_back(child);
  if (visited[p[child]])
    return 0;
  else {
    return dfs(child, p[child]);
  }
}
long long int func() {
  memset(visited, 0, sizeof(visited));
  long long int rv = 1000000007;
  for (long long i = 1; i < n + 1; ++i) {
    if (!visited[i]) {
      v.clear();
      dfs(-1, i);
      rv = min(func2(), rv);
    }
  }
  return rv;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> t;
  while (t--) {
    cin >> n;
    for (long long i = 1; i < n + 1; ++i) {
      cin >> p[i];
    }
    for (long long i = 1; i < n + 1; ++i) {
      cin >> c[i];
    }
    cout << func() << endl;
  }
  return 0;
}
