#include <bits/stdc++.h>
using namespace std;
vector<long long> par;
long long vis[200007];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int TESTS = 1;
  cin >> TESTS;
  while (TESTS--) {
    long long n;
    cin >> n;
    par = vector<long long>(n);
    vector<long long> adj[n + 1];
    for (long long i = 0; i < n; i++) {
      long long x;
      cin >> x;
      x--;
      par[i] = i;
      vis[i] = 0;
      adj[i].push_back(x);
    }
    for (long long i = 0; i < n; i++) {
      long long col;
      cin >> col;
      par[i] = col;
    }
    vector<vector<long long> > vec;
    long long ans = 1000000000;
    for (int i = 0; i < n; i++) {
      vector<long long> pat;
      long long j = i;
      while (vis[j] == 0) {
        vis[j] = 1;
        pat.push_back(j);
        j = adj[j][0];
      }
      for (long long i = 1; i <= pat.size(); i++) {
        if (pat.size() % i != 0) continue;
        for (long long j = 0; j < i; j++) {
          bool fon = true;
          for (long long k = j; k < pat.size(); k += i) {
            if (par[pat[j]] != par[pat[k]]) {
              fon = false;
              break;
            }
          }
          if (fon) {
            ans = min(ans, i);
            break;
          }
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
