#include <bits/stdc++.h>   using namespace std;   const int N = 1e6 + 5;   const long long mod = 998244353;   long long ksm(long long a, long long b) {     long long ans = 1LL;     while (b) {       if (b & 1) ans = ans * a % mod;       a = a * a % mod;       b >>= 1;     }     return ans;   }   int a[N], c[N], tmp[N], ans, tot;   bool vis[N];   bool judge(int x, int y) {     for (int i = 1; i <= x; i++) {       int t = i;       bool flag = 0;       for (int j = 1; j <= y; j++) {         if (c[tmp[t]] != c[tmp[i]]) {           flag = 1;           break;         }         t = (t + x - 1) % tot + 1;       }       if (!flag) return 1;     }     return 0;   }   void dfs(int x) {     tot = 0;     tmp[++tot] = x;     vis[x] = 1;     for (int i = a[x]; i != x; i = a[i]) tmp[++tot] = i, vis[i] = 1;     for (int i = 1; i * i <= tot; i++) {       if (tot % i == 0) {         if (judge(i, tot / i)) {           ans = min(ans, i);           return;         }         if (judge(tot / i, i)) ans = min(ans, tot / i);       }     }   }   void solve() {     int n;     scanf( %d , &n);     for (int i = 1; i <= n; i++) scanf( %d , &a[i]);     for (int i = 1; i <= n; i++) scanf( %d , &c[i]);     ans = INT_MAX;     for (int i = 1; i <= n; i++)       if (!vis[i]) dfs(i);     for (int i = 1; i <= n; i++) vis[i] = 0;     printf( %d n , ans);   }   int main() {     int _;     scanf( %d , &_);     while (_--) solve();     return 0;   }   