#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #include #include using namespace std; using Modint = atcoder::modint1000000007; template vector z_algorithm(vector A){ const int N = A.size(); vector a(N); { auto B = A; sort(B.begin(), B.end()); for(int i = 0; i < N; i++) a[i] = lower_bound(B.begin(), B.end(), A[i]) - B.begin(); } vector ans(N); for(int i = 0; i < N; i++){ const int c = a[i]; for(int j = i; j < N; j++){ if(a[j] == c && ans[j - i] == i) ans[j - i]++; } } return ans; } int main(){ int N; cin >> N; vector> A(N); for(auto& [c, a] : A) cin >> a; for(auto& [c, a] : A) cin >> c; auto Z = z_algorithm(vector(A.begin() + 1, A.end())); Z.push_back(0); vector sum(N); sum[0] = Modint::raw(A[0].second); for(int i = 1; i < N; i++) sum[i] = sum[i - 1] + Modint::raw(A[i].second); const auto [c0, a0] = A[0]; Modint ans = 0; for(int i = 0; i < N; i++) if(auto [c, a] = A[i]; c == c0){ if(a < a0){ ans += uint64_t(a) * (a + 1) / 2; continue; } ans += uint64_t(a0) * (a + a - a0 - 1) / 2; const int z = Z[i]; ans += sum[z]; if(i + 1 + z < N && A[i + 1 + z].first == A[1 + z].first){ ans += Modint::raw(min(A[i + 1 + z].second, A[1 + z].second)); } } cout << ans.val() << endl; }