#include <bits/stdc++.h>
using namespace std;
int p[200001], c[200001];
bool vis[200001];
vector<int> divisor[200001];
bool cycle[200001];
void init() {
  for (int i = 2; i < 200001; ++i) {
    for (int j = i; j < 200001; j += i) {
      divisor[j].push_back(i);
    }
  }
}
int solve2(vector<int> colors) {
  int ret = colors.size();
  bool isOne = true;
  for (int color : colors) {
    if (color != colors[0]) {
      isOne = false;
      break;
    }
  }
  if (isOne) {
    return 1;
  }
  for (int d : divisor[colors.size()]) {
    for (int i = 0; i < colors.size(); ++i) {
      cycle[i] = false;
    }
    for (int i = 0; i < colors.size(); ++i) {
      if (cycle[i]) {
        continue;
      }
      bool isGood = true;
      int fcolor = colors[i];
      int node = i;
      while (!cycle[node]) {
        if (fcolor != colors[node]) {
          isGood = false;
        }
        cycle[node] = 1;
        node = (node + d) % colors.size();
      }
      if (isGood) {
        return d;
      }
    }
  }
  return ret;
}
void solve2() {
  int n;
  scanf("%d ", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d ", &p[i]);
    vis[i] = 0;
  }
  for (int i = 1; i <= n; ++i) {
    scanf("%d ", &c[i]);
  }
  int ret = n;
  for (int i = 1; i <= n; ++i) {
    if (vis[i]) {
      continue;
    }
    int node = i;
    vector<int> colors;
    while (!vis[node]) {
      vis[node] = 1;
      colors.push_back(c[node]);
      node = p[node];
    }
    ret = min(ret, solve2(colors));
  }
  printf("%d\n", ret);
}
void solve() {
  int t;
  init();
  scanf("%d ", &t);
  while (t--) {
    solve2();
  }
}
int main() {
  solve();
  return 0;
}
