#include #include #include #include #include #include #include #include #include #include using namespace std; #define int long long int MOD = 1000000007; using lll = long long; std::pair crt(lll a1, lll m1, lll a2, lll m2) { auto normal = [](lll x, lll m) { return x >= -x ? x % m : m - (-x) % m; }; auto modmul = [&normal](lll a, lll b, lll m) { return normal(a, m) * normal(b, m) % m; }; auto extgcd = [](lll a, lll b, lll &x, lll &y) { for (lll u = y = 1, v = x = 0; a;) { lll q = b / a; std::swap(x -= q * u, u); std::swap(y -= q * v, v); std::swap(b -= q * a, a); } return b; }; lll k1, k2; lll g = extgcd(m1, m2, k1, k2); if (normal(a1, g) != normal(a2, g)) return std::make_pair(-1, -1); else { lll l = m1 / g * m2; lll x = a1 + modmul(modmul((a2 - a1) / g, k1, l), m1, l); return std::make_pair(x, l); } } std::pair crt(std::vector a, std::vector m) { lll mod = 1, ans = 0; int n = a.size(); for (int i = 0; i < n; i++) { std::tie(ans, mod) = crt(ans, mod, a[i], m[i]); if (ans == -1) return std::make_pair(-1, -1); } return std::make_pair(ans, mod); } int gcd(int a, int b) { int c; while (a != 0) { c = a; a = b%a; b = c; } return b; } int f(int a) { if (a <= 0) { return 0; } return a*(a - 1) / 2; } signed main() { cin.tie(0); ios::sync_with_stdio(false); int N; cin >> N; vector A(N); vector B(N); vector nA(N, -1); vector nB(N, -1); vector indA(N); vector indB(N); vector szA; vector szB; int res = 0; for (int i = 0; i < N; i++) { cin >> A[i]; A[i]--; } for (int i = 0; i < N; i++) { cin >> B[i]; B[i]--; } int t; int c = 0; int cc = 0; for (int i = 0; i < N; i++) { if (nA[i] == -1) { cc = 0; t = i; while (true) { nA[t] = c; indA[t] = cc; cc++; t = A[t]; if (i == t)break; } szA.push_back(cc); c++; } } c = 0; for (int i = 0; i < N; i++) { if (nB[i] == -1) { cc = 0; t = i; while (true) { nB[t] = c; indB[t] = cc; cc++; t = B[t]; if (i == t)break; } szB.push_back(cc); c++; } } map, int >, vector > mp; map, int >, int > mp2; int g; int k; pair, int > pp; for (int i = 0; i < N; i++) { //cerr << nA[i] << " " << nB[i] << " " << indA[i] << " " << indB[i] << endl; g = gcd(szA[nA[i]], szB[nB[i]]); k = (indB[i] - indA[i] + g * 1000000) % g; pp.first.first = nA[i]; pp.first.second = nB[i]; pp.second = k; mp2[pp] = (szA[nA[i]] / g) * (szB[nB[i]]); mp[pp].push_back(crt(indA[i], szA[nA[i]], (indB[i] - k + szB[nB[i]]) % szB[nB[i]], szB[nB[i]]).first); } int sz; for (auto m : mp) { sz = mp2[m.first]; sort(m.second.begin(), m.second.end()); /*for (int i = 0; i < (int)m.second.size(); i++) { cerr << m.second[i] << " "; } cerr << endl;*/ for (int i = 0; i < (int)m.second.size() - 1; i++) { res = (res + f(m.second[i + 1] - m.second[i])) % MOD; } res = (res + f(sz + m.second[0] - m.second.back())) % MOD; } cout << res << endl; }