#include <bits/stdc++.h>
using namespace std;
long long numbit(long long x) { return (1LL << x) - 1LL; }
long long getbit(long long x, long long i) { return (x >> i) & 1LL; }
long long onbit(long long x, long long i) { return x | (1LL << i); }
long long offbit(long long x, long long i) { return x & (~(1LL << i)); }
const int oo = 1000111000;
const int Nmax = 1e5 + 10;
const long long mod = 1e9 + 7;
const long double PI = 3.14159265358979323846;
int p[Nmax * 2], c[Nmax * 2];
int ch[Nmax * 2];
bool ok[Nmax * 2];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(NULL);
  int test;
  cin >> test;
  for (long long e = (1); e <= (test); e++) {
    int n;
    cin >> n;
    for (long long i = (1); i <= (n); i++) cin >> p[i];
    for (long long i = (1); i <= (n); i++) cin >> c[i];
    memset(ok, false, sizeof(ok));
    memset(ch, 0, sizeof(ch));
    int cnt = 0;
    vector<int> circle[n + 1];
    for (long long i = (1); i <= (n); i++)
      if (!ok[i]) {
        cnt++;
        int j = i;
        while (!ok[j]) {
          circle[cnt].push_back(j);
          ok[j] = true;
          j = p[j];
        }
      }
    int res = n + 1;
    for (long long i = (1); i <= (cnt); i++) {
      int it = 0;
      for (long long m = (1); m <= (circle[i].size()); m++)
        if (circle[i].size() % m == 0) {
          if (m >= res) break;
          int j = 0;
          it++;
          bool ok = false;
          while (j < circle[i].size()) {
            if (ch[circle[i][j]] == it) {
              j++;
              continue;
            }
            ok = true;
            int h = j;
            while (ok) {
              if (ch[circle[i][h]] == it ||
                  c[circle[i][j]] != c[circle[i][h]]) {
                ok = false;
                break;
              }
              ch[circle[i][h]] = it;
              h = (h + m) % circle[i].size();
              if (h == j) break;
            }
            if (ok) break;
            j++;
          }
          if (ok) {
            res = min(res, int(m));
            break;
          }
        }
    }
    cout << res << endl;
  }
}
