// kinen submit #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair P; typedef pair PP; const double PI = 3.14159265358979323846; const double EPS = 1e-12; const ll INF = 1LL<<29; const ll mod = 1e9+7; #define rep(i,n) for(int (i)=0;(i)<(ll)(n);++(i)) #define repd(i,n,d) for(ll (i)=0;(i)<(ll)(n);(i)+=(d)) #define all(v) (v).begin(), (v).end() #define pb(x) push_back(x) #define mp(x,y) make_pair((x),(y)) #define mset(m,v) memset((m),(v),sizeof(m)) #define chmin(X,Y) ((X)>(Y)?X=(Y),true:false) #define chmax(X,Y) ((X)<(Y)?X=(Y),true:false) #define fst first #define snd second #define UNIQUE(x) (x).erase(unique(all(x)),(x).end()) template ostream &operator<<(ostream &os, const vector &v){int n=v.size();rep(i,n)os<> s; void extgcd(ll x, ll y, ll &a, ll &b, ll &g){ if(y == 0){ a = 1; b = 0; g = x; } else { extgcd(y, x%y, a, b, g); swap(a, b); b -= a*x/y; } } int main(){ scanf("%d", &n); rep(i, 2) rep(j, n){ scanf("%lld", a[i]+j); a[i][j]--; } mset(p, -1); rep(i, 2) rep(j, n){ if(p[i][j] != -1) continue; ll k = a[i][j]; p[i][j] = 1; while(k != j){ c[i][k] = p[i][j]++; pr[i][k] = j; k = a[i][k]; } pr[i][j] = j; } ll res = 0; rep(j, n){ ll b[2], d; extgcd(p[0][j], p[1][j], b[0], b[1], d); ll r[2], q[2]; rep(i, 2) r[i] = c[i][j]%d; if(r[1] vv(m+1); rep(i, m) vv[i] = ix[v[i]]; v[m] = vv[0]+lp[v[0]]; rep(i, m){ ll y = vv[i+1]-vv[i]-1; res += y*(y+1)/2; res %= mod; } } cout<