#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

template<typename T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

const int N = 5e3 + 11;
const int mod = 998244353;
#define int long long
signed main () {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif // LOCAL
    int n;
    cin >> n;
    int ord = 1;
    vector<int> p(n + 1);
    bool f2= 0;
    vector<int> a(n + 1), b(n + 1);
    bool f3 = 0;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i] >> b[i];
        if (b[i] >= 0) ord = i;
        if (b[i] > 0) f2 = 1;
        if (b[i] < 0) f3 = 1;
    }
    vector<int> mxval (n + 1), mnval (n + 2);
    bool fl = 0;
    for (int i = 1; i <= n; ++i) mxval[i] = i - 1;
    int len = 0;
    for (int i = 1; i <= n; ++i) {
        cin >> p[i];
        len = max (len, p[i]);
        if (p[i] != -1) fl = 1;
        if (p[i] != -1) {
            mxval[p[i]] = min (mxval[p[i]], i - 1);
            mnval[p[i] + 1] = max(mnval[p[i] + 1], i);
        }
    }
    for (int i = n - 1; i >= 1; --i) {
        mxval[i] = min (mxval[i + 1], mxval[i]);
    }
    for (int i = 2; i<= n; ++i) {
        mnval[i] = max (mnval[i - 1], mnval[i]);
    }
    long long ans = -1e18;
    if (!fl) ans = 0;
    vector<int> dp (n + 1, -1e18);

    vector<long long> pa (n + 1), pb (n + 1);
    for (int i = 1; i <= n; ++i) pa[i] = pa[i -1 ] + a[i], pb[i] = pb[i - 1] + b[i];
    int prev = 0;
    if (!fl) dp[0] = 0;
    for (int i = 1; i <= n; ++i) {
        if (b[i] > 0) {
            vector<int> ndp (n + 1, -1e18);
            int mx = -1e18;
            for (int val = 0; val < mnval[i]; ++val) mx = max (mx, dp[val] + (pa[i- 1 ] - pa[prev]) + (pb[i - 1] - pb[prev]) * val);
            for (int val = mnval[i]; val <= mxval[i]; ++val) {
                mx = max (mx, dp[val] + (pa[i - 1] - pa[prev]) + (pb[i - 1] - pb[prev]) * val);
                ndp[val] = max (ndp[val], mx + a[i] + b[i] * val);
            }
            prev = i;
            dp = ndp;
        }
        for (int val = mnval[i]; val <= mxval[i]; ++val) {
            ans = max (ans, dp[val] + pa[i] - pa[prev] + (pb[i] - pb[prev]) * val);
        }
    }
    cout << ans << '\n';
}

