#include <bits/stdc++.h>
using namespace std;
const long long int M = 998244353;
int f(const vector<int> &v) {
  int n = v.size();
  int ans = n;
  for (int d = 1; d < v.size(); ++d) {
    if (n % d) continue;
    bool posible = false;
    for (int i = 0; i < d; ++i) {
      int c = v[i];
      bool same = true;
      for (int j = i; j < n; j += d) {
        if (v[j] == c) continue;
        same = false;
        break;
      }
      if (!same) continue;
      posible = true;
      break;
    }
    if (posible) return d;
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int T;
  for (cin >> T; T; --T) {
    int n;
    cin >> n;
    int p[n + 1];
    int c[n + 1];
    vector<int> colors[n + 1];
    for (int i = 1; i <= n; ++i) {
      cin >> p[i];
    }
    for (int i = 1; i <= n; ++i) {
      cin >> c[i];
    }
    bool vis[n + 1];
    fill(vis, vis + n + 1, false);
    for (int i = 1; i <= n; ++i) {
      int j = i;
      while (!vis[j]) {
        vis[j] = true;
        colors[i].push_back(c[j]);
        j = p[j];
      }
    }
    int ans = n;
    for (int i = 1; i <= n; ++i) {
      if (colors[i].size() > 0) {
        ans = min(ans, f(colors[i]));
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
