#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
long long T, n, p[200008], c[200008];
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cin >> T;
  for (long long t = (0); t < (T); t++) {
    cin >> n;
    for (long long i = (1); i <= (n); i++) {
      cin >> p[i];
    }
    for (long long i = (1); i <= (n); i++) {
      cin >> c[i];
    }
    long long ans = INF;
    bool use[n + 1];
    memset(use, 0, sizeof(use));
    for (long long i = (1); i <= (n); i++) {
      if (!use[i]) {
        long long at = i;
        vector<long long> seq;
        use[i] = true;
        seq.push_back(i);
        while (p[at] != i) {
          use[p[at]] = true;
          seq.push_back(p[at]);
          at = p[at];
        }
        long long m = seq.size();
        for (long long k = 1; k * k <= m; k++) {
          if (m % k == 0) {
            for (long long j = (0); j < (k); j++) {
              long long st = seq[j];
              bool ok = true;
              for (long long l = (0); l < (m / k); l++) {
                if (c[seq[j + k * l]] != c[st]) {
                  ok = false;
                }
              }
              if (ok) {
                ans = min(ans, k);
              }
            }
            for (long long j = (0); j < (m / k); j++) {
              long long st = seq[j];
              bool ok = true;
              for (long long l = (0); l < (k); l++) {
                if (c[seq[j + (m / k) * l]] != c[st]) {
                  ok = false;
                }
              }
              if (ok) {
                ans = min(ans, m / k);
              }
            }
          }
        }
      }
    }
    cout << (ans) << endl;
  }
  return 0;
}
