#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 2e5 + 10;
const int inf = 0x3f3f3f3f;
int p[maxn], c[maxn];
bool vis[maxn];
vector<int> a;
vector<int> factor;
int solve() {
  factor.clear();
  factor.push_back(1);
  for (int i = 2; i * i <= a.size(); i++) {
    if (a.size() % i != 0) continue;
    factor.push_back(i);
    factor.push_back(a.size() / i);
  }
  int ans = a.size();
  for (int i : factor) {
    for (int j = (0); j <= (i - 1); j++) {
      int now = j;
      bool f = true;
      for (int k = (1); k <= (a.size() / i); k++) {
        if (c[a[now]] != c[a[j]]) {
          f = false;
          break;
        }
        now += i;
        now %= a.size();
      }
      if (f) ans = min(ans, i);
    }
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    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];
    }
    int ans = inf;
    for (int i = (1); i <= (n); i++) {
      if (!vis[i]) {
        a.clear();
        a.push_back(i);
        vis[i] = true;
        int pos = p[i];
        while (pos != i) {
          a.push_back(pos);
          vis[pos] = true;
          pos = p[pos];
        }
        ans = min(ans, solve());
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
