#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1), eps = 1e-6;
const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
const int N = 2e5 + 5, M = 2e6 + 5, mod = 1e9 + 7;
int n, res;
int p[N], c[N];
vector<int> color;
bool vis[N];
void get_res(int n, int d) {
  for (int i = 0; i < d; i++) {
    bool success = true;
    for (int j = i + d; j < n; j += d)
      if (color[i] != color[j]) {
        success = false;
        break;
      }
    if (success) {
      res = min(res, d);
      break;
    }
  }
  return;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  int T;
  cin >> T;
  while (T--) {
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> p[i];
      vis[i] = false;
    }
    for (int i = 1; i <= n; i++) cin >> c[i];
    res = n;
    for (int i = 1; i <= n; i++)
      if (!vis[i]) {
        color.clear();
        for (int j = i; !vis[j]; j = p[j]) {
          vis[j] = true;
          color.push_back(c[j]);
        }
        int sz = color.size();
        for (int i = 1; i <= sz / i; i++)
          if (sz % i == 0) {
            get_res(sz, i);
            if (i != sz / i) get_res(sz, sz / i);
          }
      }
    cout << res << endl;
  }
  return 0;
}
