#include using namespace std; //* ATCODER #include using namespace atcoder; typedef modint998244353 mint; //*/ /* BOOST MULTIPRECISION #include using namespace boost::multiprecision; //*/ typedef long long ll; #define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++) #define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--) template bool chmin(T &a, const T &b) { if (a <= b) return false; a = b; return true; } template bool chmax(T &a, const T &b) { if (a >= b) return false; a = b; return true; } template T max(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]); return ret; } template T min(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]); return ret; } template T sum(vector &a){ T ret = 0; for (int i=0; i<(int)a.size(); i++) ret += a[i]; return ret; } struct S { ll val, sum; }; S op(S a, S b){ if (a.val < b.val) return a; if (a.val > b.val) return b; return S{a.val, a.sum + b.sum}; } S e(){ return S{(ll)1e18, 0}; } S mapping(ll f, S x) { return S{x.val + f, x.sum}; } ll composition(ll g, ll f){ return g + f; } ll id(){ return 0; } // importbisect template int bisect_left(vector &X, T v){ return lower_bound(X.begin(), X.end(), v) - X.begin(); } template int bisect_right(vector &X, T v){ return upper_bound(X.begin(), X.end(), v) - X.begin(); } // ----- int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector a(n), b(n); rep(i,0,n){ cin >> a[i]; } rep(i,0,n){ cin >> b[i]; } const int mx = 400050; lazy_segtree seg(vector(n, S{0,1})); vector bucket_a(mx, vector(0)); vector bucket_b(mx, vector(0)); rep(i,0,n){ bucket_a[a[i]].push_back(i); bucket_b[b[i]].push_back(i); } vector> now_intervals(mx, pair(0,0)); auto update = [&](int i, int l) -> void { int x = bisect_left(bucket_a[i], l); int y = bisect_left(bucket_b[i], l); int f = n; int g = n; if (x < (int)bucket_a[i].size()) { f = bucket_a[i][x]; } if (y < (int)bucket_b[i].size()) { g = bucket_b[i][y]; } if (f > g) swap(f, g); seg.apply(now_intervals[i].first, now_intervals[i].second, -1); now_intervals[i] = pair(f, g); seg.apply(now_intervals[i].first, now_intervals[i].second, +1); }; rep(i,0,mx){ update(i, 0); } ll ans = 0; rep(i,0,n){ S g = seg.prod(i, n); if (g.val == 0) { ans += g.sum; } update(a[i], i+1); update(b[i], i+1); } cout << ans << '\n'; }