#include <bits/stdc++.h>
using namespace std;
using ll = long long;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<int> p(n), c(n);
    for (int &i : p) cin >> i;
    for (int &i : c) cin >> i;
    vector<vector<int>> cycles;
    int sol = 1e9;
    vector<bool> vis(n);
    for (int i = 0; i < n; i++) {
      if (vis[i]) continue;
      vector<int> tmp;
      tmp.push_back(p[i] - 1);
      int cur = p[i] - 1;
      vis[i] = 1;
      while (cur != p[i] - 1 || tmp.size() == 1) {
        if (p[cur] - 1 == cur) {
          break;
        }
        vis[cur] = 1;
        cur = p[cur] - 1;
        tmp.push_back(cur);
      }
      if (tmp.size() > 1) tmp.pop_back();
      cycles.push_back(tmp);
    }
    for (auto v : cycles) {
      vector<int> div;
      for (int i = 1; i <= sqrt(v.size()); i++) {
        if (v.size() % i == 0) {
          div.push_back(i);
          div.push_back(v.size() / i);
        }
      }
      for (int k : div) {
        for (int i = 0; i < k; i++) {
          int cur = i;
          int cc = c[v[i]];
          bool b = true;
          do {
            cur = (cur + k) % v.size();
            if (c[v[cur]] != cc) {
              b = false;
              break;
            }
          } while (cur != i);
          if (b) {
            sol = min(sol, k);
          }
        }
      }
    }
    cout << sol << "\n";
  }
}
