#include <bits/stdc++.h>
using namespace std;
int t, n, p[200005], c[200005];
vector<int> h[200005];
int si[200005];
int visit[200005];
int cnt;
int ans = 1000000;
int main() {
  cin >> t;
  while (t--) {
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> p[i];
    }
    for (int i = 1; i <= n; i++) {
      cin >> c[i];
    }
    for (int i = 1; i <= n; i++) {
      if (!visit[i]) {
        int now = i;
        cnt++;
        visit[now] = 1;
        h[cnt].push_back(now);
        si[cnt]++;
        now = p[now];
        while (now != i) {
          si[cnt]++;
          h[cnt].push_back(now);
          visit[now] = 1;
          now = p[now];
        }
      }
    }
    for (int i = 1; i <= cnt; i++) {
      int temp = si[i];
      for (int j = 1; j * j <= temp; j++) {
        if (temp % j == 0) {
          int flag = 0;
          for (int k = 0; k <= j - 1; k++) {
            for (int mm = k + j; mm < si[i]; mm += j) {
              if (c[h[i][mm]] != c[h[i][mm - j]]) {
                flag = 1;
                break;
              }
            }
            if (flag == 0) {
              ans = min(ans, j);
            }
            flag = 0;
          }
          flag = 0;
          int j1 = temp / j;
          for (int k = 0; k <= j1 - 1; k++) {
            for (int mm = k + j1; mm < si[i]; mm += j1) {
              if (c[h[i][mm]] != c[h[i][mm - j1]]) {
                flag = 1;
              }
            }
            if (flag == 0) {
              ans = min(ans, j1);
            }
            flag = 0;
          }
        }
      }
    }
    cout << ans << endl;
    ans = 1000000;
    cnt = 0;
    for (int i = 1; i <= n; i++) {
      si[i] = visit[i] = 0;
      h[i].clear();
    }
  }
}
