#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int n, m;
int p[N], c[N];
bool ok[N];
int cycle_color[N];
int t;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> t;
  while (t--) {
    cin >> n;
    for (int(i) = (1); (i) <= (n); ++(i)) cin >> p[i];
    for (int(i) = (1); (i) <= (n); ++(i)) cin >> c[i];
    for (int(i) = (1); (i) <= (n); ++(i)) ok[i] = false;
    int ans = INT_MAX;
    for (int(u) = (1); (u) <= (n); ++(u))
      if (!ok[u]) {
        vector<int> G;
        while (!ok[u]) {
          G.push_back(u);
          ok[u] = 1;
          u = p[u];
        }
        int m = G.size();
        ans = min(ans, m);
        for (int i = 0; i < min(ans, (int)sqrt(m)); ++i) {
          i++;
          if (m % i == 0) {
            for (int j = 0; j < i; ++j) cycle_color[j] = c[G[j]];
            for (int j = i; j < G.size(); ++j)
              if (cycle_color[j % i] != c[G[j]]) cycle_color[j % i] = -1;
            for (int j = 0; j < i; ++j)
              if (cycle_color[j] != -1) ans = min(ans, i);
            i = m / i;
            for (int j = 0; j < i; ++j) cycle_color[j] = c[G[j]];
            for (int j = i; j < G.size(); ++j)
              if (cycle_color[j % i] != c[G[j]]) cycle_color[j % i] = -1;
            for (int j = 0; j < i; ++j)
              if (cycle_color[j] != -1) ans = min(ans, i);
            i = m / i;
          }
          i--;
        }
      }
    cout << ans << '\n';
  }
}
