#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define loop(i,a,b) for(int i=a;i pii; typedef vector vi; typedef vector vvi; typedef vector vp; typedef vector vvp; typedef vector vs; typedef vector vd; typedef tuple tp; typedef vector vt; typedef vector vvd; typedef pair pip; typedef vectorvip; const double PI=acos(-1); const double EPS=1e-7; const int inf=1e8; const ll INF=1e16; int dx[]={0,1,0,-1}; int dy[]={1,0,-1,0}; ll gcd(ll a,ll b){ return (b==0?a:gcd(b,a%b)); } ll lcm(ll a,ll b){ return a/gcd(a,b)*b; } ll n,size,co; vvi in,info,siz; vi used; void f(int a,int b){ int t=a; do{ if(used[t])break; used[t]=true; info[b*2][t]=co; info[b*2+1][t]=size++; t=in[b][t]; }while(1); } int main(){ cin>>n; assert(1<=n&&n<=100000); in=vvi(2,vi(n));//a,b info=vvi(4,vi(n));//numa,in_numa,numb,in_numb siz=vvi(2);//num_loop rep(i,2)rep(j,n)cin>>in[i][j]; rep(i,2)rep(j,n)assert(1<=in[i][j]&&in[i][j]<=n); rep(i,2)rep(j,n)in[i][j]--; rep(i,2){ vi asr(n); rep(j,n){ if(asr[in[i][j]])assert(0); asr[in[i][j]]=1; } } rep(i,2){ used=vi(n); size=0,co=0;//loop_size,num_loop rep(j,n)if(used[j]==0){ size=0; f(j,i); siz[i].pb(size); co++; } } mapma; rep(i,n){ ll gc_d=gcd(siz[0][info[0][i]],siz[1][info[2][i]]); ll t=(info[1][i]%gc_d-info[3][i]%gc_d+gc_d)%gc_d; ma[mt(info[0][i],info[2][i],t)].pb(i); } ll out=0,MOD=1000000007,divby2=500000004;//divby2=埋め込み for(auto it=ma.begin();it!=ma.end();it++){ ll loop_a,loop_b,gomi; vi node=it->second; tie(loop_a,loop_b,gomi)=it->first; ll siz_a=siz[0][loop_a],siz_b=siz[1][loop_b]; ll gc_d=gcd(siz_a,siz_b); vi point(siz_a/gc_d); ll now=0; rep(i,siz_a/gc_d){ point[now]=i; (now+=siz_b/gc_d)%=siz_a/gc_d; } vi co(node.size()); rep(i,node.size()){ ll a=info[1][node[i]],b=info[3][node[i]]; ll t=(a-b+(ll)1e6*siz_a)%siz_a; co[i]=point[t/gc_d]*siz_b+b; } sort(all(co)); co.pb(lcm(siz_a,siz_b)+co[0]); rep(i,co.size()-1){ ll sa=co[i+1]-co[i]-1; (out+=sa*(sa+1)%MOD*divby2%MOD)%=MOD; } } cout<