#include <bits/stdc++.h>
using namespace std;
int main() {
  int T;
  cin >> T;
  for (int tc = 0; tc < T; ++tc) {
    int N;
    cin >> N;
    int p[N], c[N], vst[N];
    for (int i = 0; i < N; ++i) {
      cin >> p[i];
      --p[i];
    }
    for (int i = 0; i < N; ++i) {
      vst[i] = 0;
      cin >> c[i];
      --c[i];
    }
    vector<vector<int> > cycles;
    for (int i = 0; i < N; ++i) {
      if (!vst[i]) {
        vst[i] = true;
        cycles.push_back({i});
        int cur = p[i];
        while (cur != i) {
          vst[cur] = true;
          cycles[cycles.size() - 1].push_back(cur);
          cur = p[cur];
        }
      }
    }
    int res = INT_MAX;
    for (int i = 0; i < cycles.size(); ++i) {
      int M = cycles[i].size();
      for (int j = 1; j <= M; ++j) {
        if (M % j != 0) continue;
        for (int k = 0; k < j; ++k) {
          int col = c[cycles[i][k]];
          bool good = true;
          for (int m = k; m < M; m += j) {
            if (c[cycles[i][m]] != col) good = false;
          }
          if (good) res = min(res, j);
        }
      }
    }
    cout << res << "\n";
  }
}
