#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
const long long maxn = 2e5 + 5;
const int inf = (int)1e9 + 7;
long long fa[maxn], n, p[maxn], c[maxn], ord[maxn];
long long quan[maxn];
long long getfa(long long x) { return fa[x] == x ? x : fa[x] = getfa(fa[x]); }
void merge(long long x, long long y) { fa[getfa(x)] = getfa(y); }
int main(int argc, char const *argv[]) {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long tim, i, j, i1, j1;
  cin >> tim;
  while (tim--) {
    long long minn = inf;
    cin >> n;
    for (i = 1; i <= n; i++) {
      cin >> p[i];
      fa[i] = i;
    }
    for (i = 1; i <= n; i++) {
      cin >> c[i];
    }
    for (i = 1; i <= n; i++) {
      long long fai = getfa(i), fanex = getfa(p[i]);
      if (fai == fanex) {
        long long cnt = 0;
        quan[++cnt] = p[i];
        long long tmp = p[i];
        while (p[tmp] != p[i]) {
          quan[++cnt] = p[tmp];
          tmp = p[tmp];
        }
        for (j = 1; j <= cnt; j++) {
          if (j >= minn) break;
          if (cnt % j) {
            continue;
          }
          for (i1 = 1; i1 <= j; i1++) {
            long long tag = 1;
            long long col = c[quan[i1]];
            for (j1 = 1; j1 <= (cnt / j) - 1; j1++) {
              if (c[quan[i1 + j1 * j]] != col) {
                tag = 0;
                break;
              }
            }
            if (tag) {
              minn = min(minn, j);
              break;
            }
          }
        }
      } else {
        merge(i, p[i]);
      }
    }
    cout << minn << "\n";
  }
  return 0;
}
