#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int p[maxn], c[maxn];
int vis[maxn];
vector<int> get_circle(int st) {
  vector<int> c;
  c.push_back(st);
  vis[st] = true;
  for (int n = st; p[n] != st; n = p[n]) {
    c.push_back(p[n]);
    vis[p[n]] = true;
  }
  return c;
}
int get_ans(const vector<int>& cir) {
  auto solve = [&](int k) {
    for (int i = 0; i < k; i++) {
      bool judge = false;
      for (int j = i; (j + k) % cir.size() != i; j += k) {
        j = j % cir.size();
        if (c[cir[j]] != c[cir[(j + k) % cir.size()]]) {
          judge = true;
          break;
        }
      }
      if (!judge) return k;
    }
    return INT_MAX;
  };
  int ans = INT_MAX;
  for (int k = 1; k * k <= cir.size(); k++) {
    if (cir.size() % k == 0) {
      ans = min(ans, solve(k));
      ans = min(ans, solve(cir.size() / k));
    }
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  int T;
  cin >> T;
  while (T--) {
    int N;
    cin >> N;
    for (int i = 1; i <= N; i++) cin >> p[i];
    for (int i = 1; i <= N; i++) cin >> c[i];
    fill(vis, vis + N + 1, false);
    int ans = INT_MAX;
    for (int i = 1; i <= N; i++) {
      if (!vis[i]) ans = min(ans, get_ans(get_circle(i)));
    }
    cout << ans << "\n";
  }
}
