#include<bits/stdc++.h>
#define all(p) p.begin(),p.end()
using namespace std;
#define int long long
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    int a[n + 1], b[n + 1];
    for (int i = 1; i <= n; i++) {
        cin >> a[i] >> b[i];
    }

    int p[n + 1];
    int l[n + 1];
    int r[n + 1];
    iota(r + 1, r + n + 1, 0);
    fill(l + 1, l + n + 1, 0);
    int mxx = 0;
    for (int i = 1; i <= n; i++) {
        cin >> p[i];
        mxx = max(mxx, p[i]);
        r[p[i]] = min(r[p[i]], i - 1);
        if (p[i] != n) {
            l[p[i] + 1] = max(l[p[i] + 1], i);
        }
    }
    for (int i = 2; i <= n; i++) {
        l[i] = max(l[i], l[i - 1]);
    }
    for (int i = n - 1; i >= 1; i--) {
        r[i] = min(r[i + 1], r[i]);
    }
    int ans = -LLONG_MAX;
    if (mxx == 0) {
        ans = 0;
    }
    int prefb[n + 1];
    fill(prefb, prefb + n + 1, 0);
    prefb[0] = 0;
    int prefa[n + 1];
    fill(prefa, prefa + n + 1, 0);
    prefa[0] = 0;
    for (int i = 1; i <= n; i++) {
        prefb[i] = prefb[i - 1] + b[i];
        prefa[i] = prefa[i - 1] + a[i];
    }
    if (mxx == 0) {
        ans = 0;
    }
    vector<int>gr = {0};
    for (int i = 1; i <= n; i++) {
        if (b[i] > 0) {
            gr.push_back(i);
        }
    }
    int dp[gr.size()][n + 1];
    for (int i = 0; i < gr.size(); i++) {
        for (int j = 0; j <= n; j++) {
            dp[i][j] = -LLONG_MAX / 2;
        }
    }
    dp[0][0] = 0;
    // cout << gr.size() << endl;
    for (int i = 1; i < gr.size(); i++) {
        int mx = -LLONG_MAX / 2;
        int L = gr[i - 1] + 1, R = gr[i] - 1;
        for (int j = 0; j < gr[i]; j++) {
            if (j < gr[i - 1] || (gr[i - 1] == 0 && j == 0)) {
                mx = max(mx, dp[i - 1][j] + prefa[R] - prefa[L - 1] + j * (prefb[R] - prefb[L - 1]));
            }
            // if (l[i] <= j && j <= r[i]) {
            dp[i][j] = max(dp[i][j], mx + j * b[gr[i]] + a[gr[i]]);
            // if (i >= mxx) {
            ans = max(ans, dp[i][j]);
            // }
            // }
            // cout << dp[i][j] << ' ';
        }
        if (i == gr.size() - 1) {
            R = n + 1;
        } else {
            R = gr[i + 1];
        }
        for (int t = 0; t < gr[i]; t++) {
            for (int j = gr[i]; j < R; j++) {
                ans = max(ans, (prefa[j] - prefa[gr[i]]) + t * (prefb[j] - prefb[gr[i]]) + dp[i][t]);
            }
        }
        // cout << endl;
    }
    for (int i = 0; i < 1; i++) {
        int R;
        if (i == gr.size() - 1) {
            R = n + 1;
        } else {
            R = gr[i + 1];
        }
        for (int t = 0; t < gr[i]; t++) {
            for (int j = gr[i]; j < R; j++) {
                ans = max(ans, (prefa[j] - prefa[gr[i]]) + t * (prefb[j] - prefb[gr[i]]) + dp[i][t]);
            }
        }
    }
    cout << ans;
}