#include #include using namespace std; long long mod(long long a, long long m){ return (a%m+m)%m; } long long gcd(long long a, long long b){ return b==0 ? a : gcd(b, a%b); } long long lcm(long long a, long long b){ return a/gcd(a,b)*b; } using T = __int128; void extended_euclid(T a, T b, T& s, T& t, T& d){ if(b==0) s=a>0?1:-1, t=0, d=a<0?-a:a; else extended_euclid(b, a%b, t, s, d), t -= a/b*s; } pair crt(T a1, T m1, T a2, T m2) { if(m1%m2 == 0 and a1%m2 == a2) return {a1, m1}; T s, t, d; extended_euclid(m1, m2, s, t, d); if (a1 % d != a2 % d) return {0, -1}; return {mod(s*a2 %m2 * m1 + t*a1 %m1 * m2, m1 * m2) / d, m1 / d * m2}; } using P = vector; P operator*(const P& l, const P& r){ P p(l.size()); for(int i = 0; i < l.size(); ++i) p[i] = r[l[i]]; return p; } long long order(const P& p){ long long o = 1; vector done(p.size(), false); for(int i = 0; i < p.size(); ++i){ if(done[i]) continue; int l = 0; while(!done[i]) done[i] = true, i = p[i], ++l; o = lcm(o, l); } return o; } int main(){ int n; cin >> n; P a(n), b(n); for(auto &x : a) cin >> x, --x; for(auto &x : b) cin >> x, --x; auto ab = a*b; // Solve for even number of turns. auto even = 2*order(ab); // Solve for odd number of turns: // The cycle structure of A*B must become equal to that of A^-1 pair odd{0,1}; P ai(n); for(int i = 0; i < n; ++i) ai[a[i]] = i; for(int i = 0; i < n; ++i){ int target = ai[i]; int period = 0, offset = -1, j = i; do{ if(j==target) offset = period; j = ab[j], ++period; } while(j != i); // Make sure that the rest of the cycle also maps correctly after // rotating. for(int k = 0; offset >= 0 and k < period; ++k){ if(ai[i] != target) offset = -1; i = ab[i]; target = ab[target]; } if(offset == -1){ cout << even << endl; return 0; } odd = crt(odd.first, odd.second, offset, period); if(odd.second == -1){ cout << even << endl; return 0; } } cout << min(even, 2*(long long)odd.first+1) << endl; }