#include <bits/stdc++.h>
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma comment(linker, "/stack:200000000")
using namespace std;
void io() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
}
int t, n, ans;
int p[300010], c[300010];
int main() {
  io();
  cin >> t;
  for (int ii = 1; ii <= t; ++ii) {
    cin >> n;
    ans = n;
    for (int i = 0; i <= (n - 1); ++i) cin >> p[i], --p[i];
    for (int i = 0; i <= (n - 1); ++i) cin >> c[i];
    for (int i = 0; i <= (n - 1); ++i) {
      if (p[i] == -1) continue;
      vector<int> vec;
      for (int j = i; p[j] != -1;) {
        vec.emplace_back(c[j]);
        int to = p[j];
        p[j] = -1;
        j = to;
      }
      for (int j = 1; j <= vec.size(); ++j) {
        if (vec.size() % j) continue;
        for (int s = 0; s <= (j - 1); ++s) {
          bool f = true;
          for (int k = s; k < vec.size(); k += j) {
            if (vec[k] != vec[s]) {
              f = false;
              break;
            }
          }
          if (f) {
            ans = min(ans, j);
            break;
          }
        }
      }
    }
    cout << ans << '\n';
  }
}
