#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
const int inf = 10000;
const int mod = 1e9 + 7;
int p[maxn], c[maxn], vis[maxn], n;
vector<int> d[maxn];
int main() {
  for (int i = 1; i <= 2e5; i++)
    for (int j = i; j <= 2e5; j += i) d[j].push_back(i);
  int t;
  scanf("%d", &t);
  for (int i = 1; i <= t; ++i) {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%d", p + i);
    for (int i = 1; i <= n; ++i) scanf("%d", c + i), vis[i] = 0;
    int ans = n + 1;
    for (int i = 1; i <= n; ++i)
      if (!vis[i]) {
        int u = i;
        vector<int> cycle;
        while (!vis[u]) {
          cycle.push_back(c[u]);
          vis[u] = 1;
          u = p[u];
        }
        int l = ((int)(cycle).size());
        for (auto k : d[l])
          for (int j = 0; j < k; j++) {
            bool flag = 1;
            for (int r = j; r < l; r += k) flag &= cycle[r] == cycle[j];
            if (flag) ans = min(ans, k);
          }
      }
    printf("%d\n", ans);
  }
  return 0;
}
