#include #include #include #include #include using namespace std; const long long mod = 1e9 + 7; long long gcd(long long x, long long y) { if (y == 0) return x; return gcd(y, x % y); } long long lcm(long long x, long long y) { return x / gcd(x, y) * y; } vector> cycle(vector a) { const int n = a.size(); vector> ret(n); vector vis(n); for (int i = 0; i < n; i++) { if (vis[i]) continue; for (int k = i; !vis[k]; k = a[k]) { ret[i].push_back(k); vis[k] = true; } } return ret; } long long modinv(long long a, long long m) { long long b = m, x = 1, y = 0; while (b != 0) { long long q = a / b; a -= b * q; x -= y * q; std::swap(a, b); std::swap(x, y); } return x < 0 ? x + m : x; } long long crt(long long a1, long long m1, long long a2, long long m2) { long long v = (a2 - a1) * modinv(m1, m2) % m2; if (v < 0) v += m2; return a1 + v * m1; } map factors(long long n) { map ret; for (int i = 2; i * i <= n; i++) { while (n % i == 0) { ret[i]++; n /= i; } } if (n != 1) ret[n] = 1; return ret; } int power(int a, int b) { int ret = 1; for (int i = 0; i < b; i++) { ret *= a; } return ret; } long long crt_g(long long a1, long long m1, long long a2, long long m2) { auto f1 = factors(m1); auto f2 = factors(m2); int M1 = 1; int M2 = 1; set st; for (auto kv : f1) st.insert(kv.first); for (auto kv : f2) st.insert(kv.first); for (int k : st) { if (f1[k] >= f2[k]) { M1 *= power(k, f1[k]); } else { M2 *= power(k, f2[k]); } } return crt(a1 % M1, M1, a2 % M2, M2); } int main() { int n; cin >> n; vector a(n), b(n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); a[i]--; } for (int i = 0; i < n; i++) { scanf("%d", &b[i]); b[i]--; } vector> cycleA = cycle(a); vector> cycleB = cycle(b); vector rootA(n), rootB(n); vector xa(n), xb(n); for (int i = 0; i < n; i++) { for (int j = 0; j < cycleA[i].size(); j++) { xa[cycleA[i][j]] = j; rootA[cycleA[i][j]] = i; } for (int j = 0; j < cycleB[i].size(); j++) { xb[cycleB[i][j]] = j; rootB[cycleB[i][j]] = i; } } map, vector> mp; for (int i = 0; i < n; i++) { mp[make_pair(rootA[i], rootB[i])].push_back(i); } long long ans = 0; for (auto kv : mp) { int A = kv.first.first; int B = kv.first.second; int lenA = cycleA[A].size(); int lenB = cycleB[B].size(); long long G = gcd(lenA, lenB); long long L = lcm(lenA, lenB); map> mp2; for (int i : kv.second) { int d = (xb[i] - xa[i]) % G; if (d < 0) d += G; mp2[d].push_back(i); } for (auto kv2 : mp2) { vector xs; for (int i : kv2.second) { int x = xa[i]; int y = xb[i] - kv2.first; if (y < 0) y += lenB; xs.push_back(crt_g(x, lenA, y, lenB)); } sort(xs.begin(), xs.end()); xs.push_back(xs[0] + L); for (int i = 0; i + 1 < xs.size(); i++) { long long d = (xs[i + 1] - xs[i]) % mod; ans += d * (d + mod - 1) % mod * ((mod + 1) / 2); ans %= mod; } } } cout << ans << endl; }