#include <bits/stdc++.h>
using namespace std;
int a[200007], b[200007];
int vis[200007];
int loop[200007];
int res;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    res = 1e9;
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i];
    for (int i = 1; i <= n; ++i) cin >> b[i];
    for (int i = 1; i <= n; ++i) vis[i] = 0;
    for (int i = 1; i <= n; ++i) {
      if (vis[i]) continue;
      int ans = 1;
      int now = i;
      int to = a[i];
      vis[i] = 1;
      vis[a[i]] = 1;
      loop[1] = b[now];
      loop[2] = b[to];
      while (to != now) {
        to = a[to];
        vis[to] = 1;
        ++ans;
        loop[1 + ans] = b[to];
      }
      for (int j = 1; j * j <= ans; ++j) {
        if (ans % j) continue;
        int flag = 0;
        for (int k = 1; k <= j; ++k) {
          flag = 0;
          for (int l = k + j; l <= ans; l += j) {
            if (loop[l] != loop[l - j]) {
              flag = 1;
            }
          }
          if (!flag) {
            res = min(res, j);
            break;
          }
        }
        for (int k = 1; k <= ans / j; ++k) {
          flag = 0;
          for (int l = k + ans / j; l <= ans; l += ans / j) {
            if (loop[l] != loop[l - ans / j]) {
              flag = 1;
            }
          }
          if (!flag) {
            res = min(res, ans / j);
            break;
          }
        }
      }
      res = min(res, ans);
    }
    cout << res << "\n";
  }
  return 0;
}
