#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, vector<pair<T, T>> &v) {
  int n = v.size();
  for (int i = 0; i < n; i++) os << v[i].first << ' ' << v[i].second << "\n";
  return os;
}
template <typename T>
ostream &operator<<(ostream &os, vector<T> &v) {
  int n = v.size();
  for (int i = 0; i < n; i++) os << v[i] << " ";
  os << '\n';
  return os;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &v) {
  int n = v.size();
  for (int i = 0; i < n; i++) is >> v[i];
  return is;
}
long long mod = 1e9 + 7;
const int MAX = 2 * 1e5 + 5;
vector<int> divisors[MAX];
void preprocessing() {
  for (int i = 1; i < MAX; i++) {
    for (int j = i * 2; j < MAX; j += i) {
      divisors[j].push_back(i);
    }
  }
}
vector<vector<int>> findCycles(vector<int> v) {
  int n = v.size();
  vector<vector<int>> res;
  vector<int> currentCycle, visited(n, 0);
  for (int i = 0; i < n; i++) {
    if (!visited[i]) {
      int j = i;
      while (v[j] != i + 1) {
        visited[j] = 1;
        currentCycle.push_back(j);
        j = v[j] - 1;
      }
      visited[j] = 1;
      currentCycle.push_back(j);
      res.push_back(currentCycle);
      currentCycle.clear();
    }
  }
  return res;
}
vector<vector<int>> putColorInCycle(vector<vector<int>> cycles,
                                    vector<int> color) {
  vector<vector<int>> res;
  for (auto cycle : cycles) {
    vector<int> colorOfThisCycle;
    for (auto vertex : cycle) {
      colorOfThisCycle.push_back(color[vertex]);
    }
    res.push_back(colorOfThisCycle);
  }
  return res;
}
bool isSame(vector<int> colors) {
  int col = colors[0];
  for (auto color : colors) {
    if (color != col) return false;
  }
  return true;
}
vector<int> multiply(vector<int> a, vector<int> b) {
  vector<int> c;
  for (auto el : a) {
    c.push_back(b[el - 1]);
  }
  return c;
}
vector<int> po(vector<int> p, int k) {
  if (k == 1)
    return p;
  else
    return multiply(po(p, k - 1), p);
}
int minCycle(vector<int> v) {
  int n = v.size();
  for (auto divisor : divisors[n]) {
    for (int i = 0; i < divisor; i++) {
      int col = v[i], flag = 1;
      for (int j = i; j < n; j += divisor) {
        if (col != v[j]) {
          flag = 0;
          break;
        }
      }
      if (flag) {
        return divisor - 1;
      }
    }
  }
  return n - 1;
}
void solvetestcase() {
  long long n;
  cin >> n;
  vector<int> p(n), c(n);
  cin >> p >> c;
  vector<vector<int>> cycles = findCycles(p);
  vector<vector<int>> colorInCycle = putColorInCycle(cycles, c);
  int mn = n - 1;
  for (auto cycle : colorInCycle) {
    mn = min(mn, minCycle(cycle));
  }
  cout << mn + 1 << '\n';
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  preprocessing();
  int t = 1;
  cin >> t;
  for (int T = 1; T < t + 1; T++) {
    solvetestcase();
  }
};
