#include <bits/stdc++.h>
using namespace std;
const long long maxn = 210000;
const long long inf = 1e9 + 7;
long long T;
long long n;
long long p[maxn];
long long c[maxn];
long long us[maxn];
vector<long long> cir[maxn];
long long Ch(vector<long long> &seq, long long to, long long st) {
  long long tot = seq.size();
  for (long long i = st; i + to < tot; i += to)
    if (c[seq[i]] != c[seq[i + to]]) return 0;
  return 1;
}
long long Che(vector<long long> &seq, long long to) {
  for (long long i = 0; i < to; i++)
    if (Ch(seq, to, i)) return 1;
  return 0;
}
void ins(long long x, long long tot) {
  long long now = x;
  while (!us[now]) {
    us[now] = 1;
    cir[tot].push_back(now);
    now = p[now];
  }
  return;
}
long long check(vector<long long> &seq) {
  long long tot = seq.size();
  long long res = inf;
  for (long long i = 1; i * i <= tot; i++) {
    if (tot % i != 0) continue;
    if (Che(seq, i)) res = min(res, i);
    if (Che(seq, tot / i)) res = min(res, tot / i);
  }
  return res;
}
signed main() {
  scanf("%lld", &T);
  for (long long am = 1; am <= T; am++) {
    scanf("%lld", &n);
    for (long long i = 0; i <= n; i++) us[i] = 0, cir[i].clear();
    for (long long i = 1; i <= n; i++) scanf("%lld", &p[i]);
    for (long long i = 1; i <= n; i++) scanf("%lld", &c[i]);
    long long tot = 0;
    long long ans = inf;
    for (long long i = 1; i <= n; i++) {
      if (us[i]) continue;
      ins(i, ++tot);
      ans = min(ans, check(cir[tot]));
    }
    if (ans >= inf)
      printf("-1\n");
    else
      printf("%lld\n", ans);
  }
  return 0;
}
