#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 = long long; pair crt(T a1, T m1, T a2, T m2) { // Make sure m1 is the larger of the two. // TLE: m1 is actually the smaller one, so we loop much more. if (m1 > m2) swap(m1, m2), swap(a1, a2); while (a1 % m2 != a2) a1 += m1; return {a1, lcm(m1, 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; vector done(n, false); for (int i = 0; i < n; ++i) { if (done[i]) continue; int target = ai[i]; int period = 0, offset = -1; do { if (i == target) offset = period; done[i] = true; i = ab[i], ++period; } while (!done[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; }