#include <bits/stdc++.h>
#include <experimental/random>

using namespace std;
using ll = long long;
using ld = long double;

const ll INF = 2e18, MOD = 998244353;

void solve();

int main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int q = 1;
    // cin >> q;
    while (q--) {
        solve();
    }
}

void solve() {
    ll n;
    cin >> n;
    vector<ll> a(n), b(n);
    vector<ll> pref = {0};
    for (int i = 0; i < n; i++) {
        cin >> a[i] >> b[i];
        pref.push_back(pref.back() + b[i]);
        if (i != 0) a[i] += a[i - 1];
    }

    vector<ll> p(n), tm(n), tm2(n);
    for (int i = 0; i < n; i++) {
        tm[i] = i;
    }
    ll opt = -1;
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] != -1) {
            opt = max(opt, p[i] - 1);
        }
        if (p[i] != -1) {
            tm[p[i] - 1] = min(tm[p[i] - 1], (ll)i);
            if (p[i] < n) {
                tm2[p[i]] = max(tm2[p[i]], (ll)(i + 1));
            }
        }
    }

    for (int i = 1; i < n; i++) {
        tm2[i] = max(tm2[i], tm2[i - 1]);
    }

    for (ll i = n - 2; i >= 0; i--) {
        tm[i] = min(tm[i], tm[i + 1]);
    }

    for (int i = 0; i < n; i++) {
        if (tm[i] < tm2[i]) {
            exit(-1);
        }
    }
    
    ll ans = -INF;

    if (opt == -1) {
        opt = 0;
        ans = 0;
    }

    vector<pair<ll, ll>> st;
    for (int k = 0; k < n; k++) {
        ll nw = 0;
        vector<ll> elem(k + 1, -1);
        ll pred = 0;
        for (int i = k; i >= 0; i--) {
            nw += b[i];
            if (nw > pred) {
                elem[i] = tm[i];
                pred = nw;
            }
        }
        for (int i = 0; i <= k; i++) {
            if (i != 0) {
                elem[i] = max(elem[i], elem[i - 1]);
            }
            elem[i] = max(elem[i], tm2[i]);
        }
        ll sm = 0;
        ll lst = 0;
        for (int i = 0; i <= k; i++) {
            sm += (pref[k + 1] - pref[i]) * (elem[i] - lst);
            lst = elem[i];
        }
        if (k >= opt) {
            ans = max(ans, a[k] + sm);
        }
    }

    cout << ans;
}