#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> p, c, l;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int T;
  cin >> T;
  vector<int> ans;
  while (T--) {
    cin >> n;
    p.resize(n);
    c.resize(n);
    for (auto &x : p) {
      cin >> x;
      x--;
    }
    for (auto &x : c) cin >> x;
    vector<bool> seen(n, false);
    m = 1e6;
    for (int i = 0; i < n; i++) {
      if (seen[i]) continue;
      int pos = i;
      l.resize(0);
      while (!seen[pos]) {
        l.push_back(c[pos]);
        seen[pos] = true;
        pos = p[pos];
      }
      for (int s = 1; s <= l.size(); s++) {
        if (l.size() % s != 0) continue;
        vector<bool> works(s, true);
        vector<int> col(s, -1);
        for (int ii = 0; ii < l.size(); ii++) {
          if (col[ii % s] == -1) col[ii % s] = l[ii];
          if (col[ii % s] != l[ii]) works[ii % s] = false;
        }
        for (auto x : works)
          if (x) m = min(m, s);
      }
    }
    ans.push_back(m);
  }
  for (auto x : ans) cout << x << endl;
  return 0;
}
