#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int ll
const ll inf = 1e18;

void solve() {
    int n;
    cin >> n;
    vector<int> a(n + 1), b(n + 1);
    bool biless0 = true;
    bool bimore0 = true;
    for (int i = 1; i <= n; i++) {
        cin >> a[i] >> b[i];
        biless0 &= b[i] <= 0;
        bimore0 &= b[i] >= 0;
    }
    vector<int> p(n + 1);
    vector<int> mi(n + 2), ma(n + 1, inf);
    int mink = 0;
    for (int i = 1; i <= n; i++) {
        cin >> p[i];
        mink = max(mink, p[i]);
        ma[i] = min(ma[i], i - 1);
        if (p[i] == -1) {
            continue;
        }
        ma[p[i]] = min(ma[p[i]], i - 1);
        mi[p[i] + 1] = max(mi[p[i] + 1], i);
    }
    for (int i = 1; i <= n; i++) {
        mi[i] = max(mi[i - 1], mi[i]);
    }
    for (int i = n - 1; i >= 1; i--) {
        ma[i] = min(ma[i], ma[i + 1]);
    }

    int ans = -inf;
    if (mink == 0) {
        ans = 0;
    }

    if (biless0) {
        int cur = 0;
        for (int i = 1; i <= n; i++) {
            cur += a[i] + b[i] * mi[i];
            ans = max(ans, cur);
        }
        cout << ans;
        return;
    }

    if (bimore0) {
        int cur = 0;
        
    }

    vector<vector<int> > dp(n + 1, vector<int>(n + 1, -inf));
    dp[0][0] = 0;
    for (int i = 0; i <= n; i++) {
        if (i != 0) {
            for (int t = mi[i]; t <= ma[i]; t++) {
                int add = a[i] + b[i] * t;
                dp[i][t] = max(dp[i][t], dp[i - 1][t] + add);
                if (i >= mink) {
                    ans = max(ans, dp[i][t]);
                }
            }
        }
        for (int t = mi[i] + 1; t <= n; t++) {
            dp[i][t] = max(dp[i][t], dp[i][t - 1]);
        }
    }
    cout << ans;
}

signed main() {
    cin.tie(0);
    ios_base::sync_with_stdio(false);
    int t = 1;
    // cin >> t;
    for (int ts = 1; ts <= t; ts++) {
        solve();
    }
}
