#include<bits/stdc++.h>

using namespace std;

#define int long long

const int INF = 1e18;

signed main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    int n;
    cin >> n;
    vector<pair<int, int>> el(n);
    for (int i = 0; i < n; i++) {
        cin >> el[i].first >> el[i].second;
    }
    vector<int> p(n), mnt(n), curp(n + 1), mx(n, INF);
    int mxp = 0;
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] != -1) {
            curp[p[i]] = max(curp[p[i]], i + 1);
            mx[p[i] - 1] = min(mx[p[i] - 1], i + 1);
            mxp = max(mxp, p[i]);
        }
    }
    int nowmx = 0;
    for (int i = 0; i < n; i++) {
        nowmx = max(nowmx, curp[i]);
        mnt[i] = nowmx;
    }
    // for (auto u : mnt) cout << u << ' ';
    // cout << '\n';
    // for (auto u : mx) cout << u << ' ';
    // cout << endl;
    vector<vector<int>> dp(n + 1, vector<int>(n, -INF));
    dp[0][0] = 0;
    for (int i = 1; i <= n; i++) {
        int it = 0, curmx = -INF;
        for (int j = mnt[i - 1]; j <  min(i, mx[i - 1]); j++) {
            while (it <= j) {
                curmx = max(curmx, dp[i - 1][it]);
                it++;
            }
            // int curmx = -INF;
            // for (int k = 0; k <= j; k++) {
            //     curmx = max(curmx, dp[i - 1][k]);
            // }
            dp[i][j] = curmx + el[i - 1].first + el[i - 1].second * j;
        }
    }
    int ans = -INF;
    for (int i = mxp; i <= n; i++) {
        for (auto u : dp[i]) {
            ans = max(ans, u);
        }
    }
    cout << ans << '\n';
}