#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int n;
int a[N], c[N];
int p[N], tmp[N];
int vis[N], vi;
bool can;
int idx, val;
vector<int> v1;
void DFS(int node, int cur) {
  v1.push_back(c[a[node]]);
  vis[node] = vi;
  if (vis[p[node]] != vi) DFS(p[node], cur + 1);
}
void solve() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= n; i++) p[a[i]] = i;
  for (int i = 1; i <= n; i++) scanf("%d", &c[i]);
  vi++;
  int ans = n;
  for (int i = 1; i <= n; i++) {
    if (vis[i] == vi) continue;
    v1.clear();
    DFS(i, 0);
    for (int k = 1; k <= (int)v1.size(); k++) {
      if ((int)v1.size() % k != 0) continue;
      for (int i = 0; i < k; i++) {
        can = true;
        for (int j = i + k; j < (int)v1.size(); j += k) {
          if (v1[j] != v1[i]) {
            can = false;
            break;
          }
        }
        if (can == true) {
          ans = min(ans, k);
          break;
        }
      }
    }
  }
  printf("%d\n", ans);
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    solve();
  }
  return 0;
}
