#include using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- int N; template class UF { public: vector par,rank; UF() {rank=vector(um,0); for(int i=0;irank[y]) return par[x]=y; rank[x]+=rank[x]==rank[y]; return par[y]=x; } }; UF<200000> uf[2]; int A[2][101010]; int id[2][101010]; vector V[2][101010]; ll mo=1000000007; map,vector> M; ll ext_gcd(ll p,ll q,ll& x, ll& y) { // get px+qy=gcd(p,q) if(q==0) return x=1,y=0,p; ll g=ext_gcd(q,p%q,y,x); y-=p/q*x; return g; } pair crt(ll a1,ll mo1,ll a2,ll mo2) { // return (x,y) y=lcm(a1,a2),x%mo1=a1,x%mo2=a2 ll g,x,y,z; g=ext_gcd(mo1,mo2,x,y); a1=(a1%mo1+mo1)%mo1;a2=(a2%mo2+mo2)%mo2; if(a1%g != a2%g) return pair(-1,0); // N/A ll lcm=mo1*(mo2/g); if(lcm(-2,0); // overflow ll v=a1+((a2-a1)%lcm+lcm)*x%lcm*(mo1/g); return make_pair(((v%lcm)+lcm) % lcm,lcm); } ll hoge(int X,int Y,vector R) { int i; int g=__gcd(X,Y); map> V; FORR(r,R) { int a=id[0][r]; int b=id[1][r]; int dif=(a-b+Y)%g; a=(a+X-dif)%X; pair tmp=crt(a,X,b,Y); V[dif].push_back(tmp.first); } ll ret=0; FORR(r,V) { vector vec=r.second; sort(ALL(vec)); vec.push_back(vec[0]+1LL*X*Y/g); FOR(i,vec.size()-1) { ll dif=vec[i+1]-vec[i]; (ret+=(dif%mo)*((dif+mo-1)%mo)%mo*((mo+1)/2))%=mo; } } return ret; } void solve() { int i,j,k,l,r,x,y; string s; cin>>N; FOR(j,2) { FOR(i,N) { cin>>A[j][i], A[j][i]--; uf[j](i,A[j][i]); } FOR(i,N) if(uf[j][i]==i) { V[j][i].push_back(i); while(A[j][V[j][i].back()]!=i) { id[j][A[j][V[j][i].back()]]=V[j][i].size(); V[j][i].push_back(A[j][V[j][i].back()]); } } } FOR(i,N) M[{uf[0][i],uf[1][i]}].push_back(i); ll ret=0; FORR(r,M) { (ret+=hoge(V[0][r.first.first].size(),V[1][r.first.second].size(),r.second))%=mo; } cout<