#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10, mod = 998244353;
int n, c[maxn], p[maxn], vis[maxn];
vector<int> d[maxn];
int main() {
  int T;
  for (int i = 1; i < maxn; i++)
    for (int j = i; j < maxn; j += i) d[j].push_back(i);
  for (scanf("%d", &T); T; T--) {
    scanf("%d", &n);
    int ans = n + 1;
    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;
    for (int i = 1; i <= n; i++)
      if (!vis[i]) {
        int u = i;
        vector<int> v;
        while (!vis[u]) {
          vis[u] = 1;
          v.push_back(c[u]);
          u = p[u];
        }
        int m = v.size();
        for (auto s : d[m])
          for (int i = 0; i < s; i++) {
            int sta = 1;
            for (int j = i; j < m; j += s) sta &= v[j] == v[i];
            if (sta) ans = min(ans, s);
          }
      }
    printf("%d\n", ans);
  }
  return 0;
}
