#pragma GCC optimize("Ofast", "unroll-loops", "omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define X first
#define Y second
const ll mod = 1000000007;
//const ll mod = 998244353;
ll pew(ll a, ll b) {
ll res = 1;
while (b>0) {
if (b&1) res = res*a%mod;
b >>= 1;
a = a*a%mod;
}
return res;
}
const ll mx = 1000000LL*1000000LL;
void solve() {
ll n;
cin >> n;
vector<ll> a(n), b(n), A(n);
for (ll i=0;i<n;i++) {
cin >> a[i];
a[i]--;
}
for (ll i=0;i<n;i++) {
cin >> b[i];
b[i]--;
}
for (ll i=0;i<n;i++) A[i] = b[a[i]];
ll G = 1;
vector<ll> was(n);
for (ll i=0;i<n;i++) {
if (was[i]==1) continue;
ll u = i, q = 0;
while (was[u]==0) {
was[u] = 1;
u = A[u];
q++;
}
G = G*q/gcd(G,q);
if (G>mx) break;
}
ll ans = mx*2+1;
ans = min(ans,G*2);
for (ll i=0;i<n;i++) was[i] = 0;
ll P = 1, r = 0;
ll F = 0;
vector<ll> obr(n);
for (ll i=0;i<n;i++) {
if (was[i]==1) continue;
ll u = i;
vector<ll> ord;
while (was[u]==0) {
was[u] = 1;
obr[u] = ord.size();
ord.push_back(u);
u = A[u];
}
ll sz = ord.size();
for (ll x: ord) {
if (obr[a[x]]==-1) {
F = 1;
break;
}
}
if (F==1) break;
ll r2 = (sz-obr[a[ord[0]]])%sz;
for (ll j=0;j<sz;j++) {
if ((obr[a[ord[j]]]+r2)%sz!=j) {
F = 1;
break;
}
}
if (F==1) break;
ll W = sz/gcd(P,sz);
ll D = W;
while (r%sz!=r2 and r<=mx) {
r += P;
D--;
if (D==0) break;
}
if (r%sz!=r2) break;
if (P<=mx) {
P *= W;
}
for (ll j=0;j<sz;j++) {
obr[ord[j]] = -1;
}
}
if (F==0) {
ans = min(ans,r*2+1);
}
if (ans>mx) {
cout << "huge\n";
return;
}
/*if (ans%2==1) {
ll W = ans/2;
vector<ll> cur = a;
while (W>0) {
if (W&1) {
vector<ll> nxt(n);
for (ll i=0;i<n;i++) nxt[i] = A[cur[i]];
cur = nxt;
}
W >>= 1;
{
vector<ll> nxt(n);
for (ll i=0;i<n;i++) nxt[i] = A[A[i]];
A = nxt;
}
}
ll ok = 1;
for (ll i=0;i<n;i++) {
if (A[i]!=i) {
ok = 0;
}
}
if (ok!=1) {
cout << "huge\n";
return;
}
}*/
cout << ans << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
int T = 1;
//cin >> T;
while (T--) solve();
return 0;
}