#include #define ll long long #define INF 1000000005 #define MOD 1000000007 #define EPS 1e-10 #define rep(i,n) for(int i=0;i<(int)(n);++i) #define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i) #define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i) #define each(a,b) for(auto (a): (b)) #define all(v) (v).begin(),(v).end() #define len(v) (int)(v).size() #define zip(v) sort(all(v)),v.erase(unique(all(v)),v.end()) #define cmx(x,y) x=max(x,y) #define cmn(x,y) x=min(x,y) #define fi first #define se second #define pb push_back #define show(x) cout<<#x<<" = "<<(x)< P; typedef pair pll; typedef vector vi; typedef vector vvi; typedef vector vl; typedef vector vd; typedef vector

vp; typedef vector vs; const int MAX_N = 100005; int sa[MAX_N],sb[MAX_N]; int ka[MAX_N],kb[MAX_N]; bool flag[MAX_N]; map mp; void extgcd(int a,int b, int& x,int& y) { if(b != 0){ extgcd(b,a%b,y,x); y -= (a/b)*x; }else{ x = 1; y = 0; } } int mod_inverse(int a,int m) { int x,y; extgcd(a,m,x,y); return (m + x % m) % m; } ll add(ll x,ll y) { return (x + y)%MOD; } ll sub(ll x,ll y) { return (x+MOD-y)%MOD; } ll mul(ll x,ll y) { return x*y%MOD; } ll gcd(ll a,ll b) { if(a % b == 0){ return b; }else{ return gcd(b,a%b); } } ll lcm(ll a,ll b) { return a / gcd(a,b) * b; } ll comp(ll n) { n %= MOD; return mul(mul(n,add(n,1)),mod_inverse(2,MOD)); } int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vi a(n),b(n); rep(i,n){ cin >> a[i]; --a[i]; } rep(i,n){ cin >> b[i]; --b[i]; } int cnt = 0; rep(i,n){ if(!flag[i]){ set st; flag[i] = true; st.insert(i); int nw = a[i]; while(nw != i){ flag[nw] = true; st.insert(nw); nw = a[nw]; } each(it,st){ ka[it] = cnt; sa[it] = len(st); } cnt++; } } cnt = 0; rep(i,n){ flag[i] = false; } rep(i,n){ if(!flag[i]){ set st; flag[i] = true; st.insert(i); int nw = b[i]; while(nw != i){ flag[nw] = true; st.insert(nw); nw = b[nw]; } each(it,st){ kb[it] = cnt; sb[it] = len(st); } cnt++; } } rep(i,n){ mp[P(ka[i],kb[i])].pb(i); } ll ans = 0; each(it,mp){ vi& vec = it.se; int num = gcd(sa[vec[0]],sb[vec[0]]); ans = add(ans,comp(add(mul(len(vec),(sb[vec[0]]/num)-1),mul(sa[vec[0]]-len(vec),sb[vec[0]]/num)))); } cout << ans << "\n"; return 0; }