#include #include #include using namespace std; #define rep(i,n) for(int i=0; i<(n); i++) int segtree_N = 1 << 18; vector segtree; vector>> segtree_queries; vector>> segtree_rollback; long long ans = 0; int N; vector A; vector B; vector> occurA; vector> occurB; void segtree_query(int l, int r, int t, int a=0, int b=0, int i=0){ if(i == 0){ a=0; b=segtree_N; i=1; } if(segtree[i] == 0) return; if(r <= a || b <= l) return; if(l <= a && b <= r){ segtree_rollback[t].push_back(make_pair(i,segtree[i])); segtree[i] = 0; return; } segtree_query(l, r, t, a, (a+b)/2, i*2); segtree_query(l, r, t, (a+b)/2, b, i*2+1); segtree_rollback[t].push_back(make_pair(i,segtree[i])); segtree[i] = segtree[i*2] + segtree[i*2+1]; } void run(int l, int r, int t){ for(auto [ql, qr] : segtree_queries[t]) segtree_query(ql, qr, t); if(l+1 == r){ if(t - segtree_N <= N){ //cout << "t = " << (t-segtree_N) << ", dans = " << (segtree[1] - (t-segtree_N)) << endl; ans += segtree[1] - (t-segtree_N); } } else{ run(l, (l+r)/2, t*2); run((l+r)/2, r, t*2+1); } reverse(segtree_rollback[t].begin(), segtree_rollback[t].end()); for(auto [i, v] : segtree_rollback[t]) segtree[i] = v; } void segtree_init(int n){ segtree_N = 1; while(segtree_N < n) segtree_N *= 2; segtree.assign(segtree_N * 2, 0); segtree_queries.assign(segtree_N * 2, {}); segtree_rollback.assign(segtree_N * 2, {}); for(int i=0; i=1; i--) segtree[i] = segtree[i*2] + segtree[i*2+1]; } void segtree_dynamic_query(int l, int r, int tl, int tr){ tl += segtree_N; tr += segtree_N; while(tl < tr){ if(tl & 1) segtree_queries[tl++].push_back(make_pair(l,r)); if(tr & 1) segtree_queries[--tr].push_back(make_pair(l,r)); tl /= 2; tr /= 2; } } int main(){ cin >> N; A.resize(N); rep(i,N){ cin >> A[i]; A[i]--; } B.resize(N); rep(i,N){ cin >> B[i]; B[i]--; } segtree_init(N); occurA.resize(400000); occurB.resize(400000); rep(i,N) occurA[A[i]].push_back(i); rep(i,N) occurB[B[i]].push_back(i); rep(t,2){ swap(A, B); swap(occurA, occurB); rep(i,N){ int a = A[i]; if(B[i] == a) continue; auto r = lower_bound(occurB[a].begin(), occurB[a].end(), i) - occurB[a].begin(); int tl = 0; if(r != 0) tl = occurB[a][r-1] + 1; int tr = i+1; int ql = i; int qr = N; if(r != occurB[a].size()) qr = occurB[a][r]; //cout << "tl = " << tl << ", tr = " << tr << ", ql = " << ql << ", qr = " << qr << endl; segtree_dynamic_query(ql, qr, tl, tr); } } run(0, segtree_N, 1); cout << ans << endl; return 0; } struct ios_do_not_sync{ ios_do_not_sync(){ ios::sync_with_stdio(false); cin.tie(nullptr); } } ios_do_not_sync_instance;