#include <bits/stdc++.h>
using namespace std;
int n;
int p[200001];
int c[200001];
int indeg[200001];
bool visited[200001];
vector<int> v;
vector<int> divisors[200001];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  for (int i = 1; i <= 200000; i++) {
    for (int j = 1; j * i <= 200000; j++) divisors[i * j].push_back(i);
  }
  while (t--) {
    cin >> n;
    for (int i = 1; i <= n; i++) {
      visited[i] = false;
      indeg[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      cin >> p[i];
      indeg[p[i]]++;
    }
    for (int i = 1; i <= n; i++) cin >> c[i];
    queue<int> q;
    for (int i = 1; i <= n; i++) {
      if (indeg[i] == 0) q.push(i);
    }
    while (!q.empty()) {
      int v = q.front();
      q.pop();
      indeg[p[v]]--;
      if (indeg[p[v]] == 0) q.push(p[v]);
      if (indeg[v] == 0) p[v] = 0;
    }
    int minim = 2000000000;
    for (int i = 1; i <= n; i++) {
      if (visited[i]) continue;
      if (p[i] == 0) continue;
      int u = i;
      v.push_back(u);
      u = p[u];
      visited[u] = true;
      while (u != i) {
        visited[u] = true;
        v.push_back(u);
        u = p[u];
      }
      int m = v.size();
      bool check;
      for (auto it : divisors[m]) {
        check = true;
        for (int j = 0; j < it; j++) {
          check = true;
          int val = j;
          val = (val + it) % m;
          while (val != j) {
            if (c[v[val]] != c[v[j]]) {
              check = false;
              break;
            }
            val += it;
            val %= m;
          }
          if (check) break;
        }
        if (check) {
          minim = (minim < it ? minim : it);
          break;
        }
      }
      v.clear();
    }
    cout << minim << "\n";
  }
}
