#include <bits/stdc++.h>
using namespace std;
int main(void) {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int T;
  cin >> T;
  for (int TN = 0; TN < T; TN++) {
    int n;
    cin >> n;
    vector<int> p(n), c(n);
    for (int i = 0; i < n; i++) {
      cin >> p[i];
      p[i]--;
    }
    for (int i = 0; i < n; i++) {
      cin >> c[i];
      c[i]--;
    }
    int ans = n;
    vector<bool> vis(n, false);
    for (int i = 0; i < n; i++) {
      if (vis[i]) continue;
      vector<int> chn;
      for (int u = i; !vis[u]; vis[u] = true, u = p[u]) chn.push_back(u);
      vector<int> dvs;
      for (int x = 1; x <= chn.size() / x; x++) {
        if (chn.size() % x == 0) {
          dvs.push_back(x);
          int y = chn.size() / x;
          if (x < y) dvs.push_back(y);
        }
      }
      for (const auto& x : dvs) {
        for (int k = 0; k < x; k++) {
          int clr = -1;
          for (int j = k; j < chn.size(); j += x) {
            if (clr < 0 || clr == c[chn[j]])
              clr = c[chn[j]];
            else {
              clr = -1;
              break;
            }
          }
          if (clr >= 0) ans = min(ans, x);
        }
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
