#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    cin >> n;
    vector<pair<long long, long long>> arr(n);
    for(int i = 0; i < n; i++) cin >> arr[i].first >> arr[i].second;
    vector<vector<long long>> dp(n);

    vector<int> p(n);
    for(int i = 0; i < n; i++) cin >> p[i];
    vector<pair<int, int>> tms(n);
    int lstt = 0, ltm = 0;
    for(int i = 0; i < n; i++) {
        if(p[i] == -1) continue;
        int tmm = i, cnt = p[i];
        for(int j = lstt; j < cnt; j++) {
            tms[j] = {ltm, tmm};
        }
        ltm = tmm + 1;
        lstt = cnt;
    }
    for(int i = lstt; i < n; i++) tms[i] = {ltm, n};

    dp[0] = vector<long long>(n, LLONG_MIN / 2);
    dp[0][0] = 0;
    int pidx = 0;
    long long negsum = 0;
    vector<long long> mxxbl(n, LLONG_MIN / 2);
    long long lastBlkMx = 0;
    mxxbl[0] = 0;
    for(int i = 1; i < n; i++) {
        if(arr[i].second <= 0) {
            negsum += arr[i].second;
            mxxbl[i] = negsum + lastBlkMx;
            continue;
        }
        dp[i] = vector<long long>(n, LLONG_MIN / 2);
        long long mxx = LLONG_MIN / 2;
        // for(int j = 0; j < tms[i].first; j++) mxx = max(mxx, dp[pidx][j]);
        for(int j = tms[i].first; j <= min(i, tms[i].second); j++) {
            mxx = max(mxx, dp[pidx][j] + negsum * j);
            dp[i][j] = max(dp[i][j], mxx + arr[i].second * j);
        }
        lastBlkMx = *max_element(dp[i].begin(), dp[i].end());
        mxxbl[i] = lastBlkMx;

        negsum = 0;
        pidx = i;
    }
    int mxx = *max_element(p.begin(), p.end()) - 1;
    long long ans = LLONG_MIN / 2;
    if(mxx < 0) ans = 0;
    // for(auto i : dp) {
    //     for(auto j : i) cout << j << ' ';
    //     cout << '\n';
    // }
    long long cs = 0;
    for(int i = 0; i < n; i++) {
        cs += arr[i].first;
        if(i < mxx) continue;
        ans = max(ans, mxxbl[i] + cs);
    }
    cout << ans << '\n';
}
