#include <bits/stdc++.h>
#define int long long
#define ll long long
#define str string
#define ld long double
#define run_vasya_run ios_base::sync_with_stdio(0) , cin.tie(0) ,cout.tie(0)
#define uint unsigned long long
#define fi first
#define se second
#define pb push_back
#define open freopen ("log.in", "r", stdin);
#define close freopen("log.out", "w", stdout);
using namespace std;
const int MOD = 10000000007;
ll _;

ll zet(priority_queue<pair <ll, ll>> z, ll l1, ll r1) {
    while (!(z.top().se <= r1 && z.top().se >= l1)) {
        z.pop();
    }

    return z.top().se;
}

main()
{
    //run_vasya_run;
    _ = 1;
    //open;
    //close;
    //cin >> _;
    while(_ --)
    {
        ll n;
        cin >> n;

        ll a[n+17], c[n+17], d[n+17] = {};
        priority_queue <pair <ll, ll>> q;

        for (ll i=1; i<=n; i++) {
            cin >> a[i];
            q.push({a[i], i});
        }
        for (ll i=1; i<=n; i++) {
            cin >> c[i];
            d[i] = d[i-1] + c[i];
        }

        ll l = 1, r = n, ans=0;

        while (l <= r) {
            while (!(q.top().se <= r && q.top().se >= l)) {
                q.pop();
            }

            ll mid = q.top().se;
            q.pop();

            if (l == mid) {
                ans += c[mid];
                r = mid - 1;
            }
            else if (r == mid) {
                ans += c[mid];
                l = mid + 1;
            }
            else {
                ll x = c[zet(q, mid + 1, r)];
                ll y = c[zet(q, l, mid - 1)];

                if (x == y) {
                    if (mid - l > r - mid) {
                        ans += c[mid];
                        l = mid + 1;
                    }
                    else if (mid - l <= r - mid) {
                        ans += c[mid];
                        r = mid - 1;
                    }
                }
                else if (x > y) {
                    ans += c[mid];
                    r = mid - 1;
                }
                else {
                    ans += c[mid];
                    l = mid + 1;
                }
            }
        }
        cout << ans << "\n";
    }
}
