#include <bits/stdc++.h>
using namespace std;
int t;
int n, a[200010], c[200010];
int vis[200010], z[200010];
vector<int> v;
void init() { memset(vis, 0, sizeof vis), z[0] = 0; }
void work() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= n; i++) scanf("%d", &c[i]);
  int ans = n;
  for (int i = 1; i <= n; i++) {
    if (vis[i]) continue;
    v.clear(), vis[i] = 1, v.push_back(i);
    int tmp = a[i];
    while (tmp != i) vis[tmp] = 1, v.push_back(tmp), tmp = a[tmp];
    int len = v.size();
    z[0] = 0;
    ans = min(ans, len);
    for (int j = 1; j <= sqrt(len); j++)
      if (len % j == 0) {
        z[++z[0]] = j;
        if (j * j != len) z[++z[0]] = len / j;
      }
    for (int j = 1; j <= z[0]; j++)
      for (int k = 0; k < z[j]; k++) {
        int flag = 1;
        for (int kk = k; kk < len; kk += z[j])
          if (c[v[k]] != c[v[kk]]) {
            flag = 0;
            break;
          }
        if (flag) {
          ans = min(ans, z[j]);
          break;
        }
      }
  }
  printf("%d\n", ans);
}
int main() {
  scanf("%d", &t);
  while (t--) init(), work();
}
