#include #define show(x) cerr << #x << " = " << x << endl using namespace std; using ll = long long; using pii = pair; using vi = vector; template ostream& operator<<(ostream& os, const vector& v) { os << "sz=" << v.size() << "\n["; for (const auto& p : v) { os << p << ","; } os << "]\n"; return os; } template ostream& operator<<(ostream& os, const pair& p) { os << "(" << p.first << "," << p.second << ")"; return os; } constexpr ll MOD = 1e9 + 7; template constexpr T INF = numeric_limits::max() / 100; class DisjointSets { public: DisjointSets(const int v) { m_parent.resize(v); m_rank.resize(v); m_size.resize(v); for (int i = 0; i < v; i++) { m_parent[i] = i; m_rank[i] = 0; m_size[i] = 1; } } bool same(const int a, const int b) { return find(a) == find(b); } int find(const int a) { if (m_parent[a] == a) { return a; } else { return m_parent[a] = find(m_parent[a]); } } void unite(const int a_, const int b_) { const int a = find(a_); const int b = find(b_); if (a == b) { return; } if (m_rank[a] > m_rank[b]) { m_parent[b] = a; m_size[a] += m_size[b]; } else { m_parent[a] = b; m_size[b] += m_size[a]; } if (m_rank[a] == m_rank[b]) { m_rank[b]++; } } int getSize(const int a) { return m_size[m_parent[a]]; } private: vector m_parent; vector m_rank; vector m_size; }; struct Cycles { int acycle; int bcycle; int mode; bool operator<(const Cycles& c) const { return (acycle != c.acycle) ? acycle < c.acycle : (bcycle != c.bcycle) ? bcycle < c.bcycle : mode < c.mode; } }; ostream& operator<<(ostream& os, const Cycles& c) { os << "acycle = " << c.acycle << ", bcycle = " << c.bcycle << ", mode = " << c.mode << endl; return os; } int main() { cin.tie(0); ios::sync_with_stdio(false); int N; cin >> N; DisjointSets auf(N); vector A(N); DisjointSets buf(N); vector B(N); for (int i = 0; i < N; i++) { cin >> A[i]; A[i]--; auf.unite(i, A[i]); } for (int i = 0; i < N; i++) { cin >> B[i]; B[i]--; buf.unite(i, B[i]); } vector aorder(N); vector aused(N, false); for (int i = 0; i < N; i++) { int pos = i; int cnt = 0; while (not aused[pos]) { aorder[pos] = cnt; aused[pos] = true; cnt++; pos = A[pos]; } } vector border(N); vector bused(N, false); for (int i = 0; i < N; i++) { int pos = i; int cnt = 0; while (not bused[pos]) { border[pos] = cnt; bused[pos] = true; cnt++; pos = B[pos]; } } map num; for (int i = 0; i < N; i++) { const int asize = auf.getSize(i); const int bsize = buf.getSize(i); const int g = gcd(asize, bsize); num[Cycles{auf.find(i), buf.find(i), (((aorder[i] - border[i]) % g) + g % g)}]++; } ll sum = 0; for (const auto& p : num) { // show(p); const int acycle = p.first.acycle; const int bcycle = p.first.bcycle; const ll asize = auf.getSize(acycle); const ll bsize = buf.getSize(bcycle); const ll count = p.second; const ll size = lcm(asize, bsize) - count; sum += (size * (size + 1) / 2); sum %= MOD; } cout << sum << endl; return 0; }