#include <bits/stdc++.h>
using namespace std;
const int N = 2 * 1e5 + 5;
int v[N];
int c[N];
bool viz[N];
bool check(int len, vector<int> v) {
  int n = v.size();
  for (int i = 0; i < len; i++) {
    int p = (i + len) % n;
    while (v[p] == v[(p + len) % n] && p != i) {
      p = (p + len) % n;
    }
    if (p == i) return true;
  }
  return false;
}
int getscore(vector<int> v) {
  int n = v.size();
  for (int d = 1; d <= n; d++) {
    if (n % d == 0) {
      if (check(d, v)) {
        return d;
      }
    }
  }
  return n;
}
void solve() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> v[i];
  }
  for (int i = 1; i <= n; i++) cin >> c[i];
  int ans = N;
  vector<int> sir;
  for (int i = 1; i <= n; i++) {
    if (viz[i] == false) {
      sir.clear();
      int p = i;
      while (viz[p] == false) {
        sir.push_back(c[p]);
        viz[p] = true;
        p = v[p];
      }
      ans = min(ans, getscore(sir));
    }
  }
  cout << ans << "\n";
  for (int i = 1; i <= n; i++) {
    viz[i] = false;
  }
}
int main() {
  int n;
  cin >> n;
  while (n--) solve();
  return 0;
}
