#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 C[2][101010]; ll mo=1000000007; set> did; ll hoge(vector X,vector Y) { map rev[2]; int i; FOR(i,X.size()) rev[0][X[i]]=i; FOR(i,Y.size()) rev[1][Y[i]]=i; int g=__gcd(X.size(),Y.size()); map> V; FOR(i,X.size()) if(rev[1].count(X[i])) { int a=rev[0][X[i]]; int b=rev[1][X[i]]; int dif=(a-b+Y.size())%g; a-=dif; ll tmp; for(tmp=b;;tmp+=Y.size()) { if(tmp%X.size()==a) break; } V[dif].push_back(tmp); } ll ret=0; FORR(r,V) { vector vec=r.second; sort(ALL(vec)); vec.push_back(vec[0]+1LL*X.size()*Y.size()/g); FOR(i,vec.size()-1) { ll dif=vec[i+1]-vec[i]; (ret+=dif*(dif-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) C[j][uf[j][i]]++; } ll ret=0; FOR(i,N) { if(did.count({uf[0][i],uf[1][i]})) continue; did.insert({uf[0][i],uf[1][i]}); vector V[2]; FOR(j,2) { V[j].push_back(i); while(A[j][V[j].back()]!=i) V[j].push_back(A[j][V[j].back()]); } (ret += hoge(V[0],V[1]))%=mo; } cout<