#include <bits/stdc++.h>

#define int long long

using namespace std;

signed main() {
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
    vector<int> q(n);
    int mxq = 0;
    for (int i = 0; i < n; i++) {
        cin >> q[i];
        if (q[i] != -1) {
            mxq = i;
        }
    }
    vector<vector<int>> p(n);
    for (int i = 0; i < n; i++) {
        if (q[i] != -1) {
            p[q[i] - 1].push_back(i);
        }
    }
    vector<int> smx(n, n - 1), smn(n, 0);
    for (int i = n - 1; i >= 0; i--) {
        if (i != n - 1) {
            smx[i] = min(smx[i + 1], i);
        }
        for (int x : p[i]) {
            smx[i] = min(smx[i], x);
        }
    }
    for (int i = 0; i < n; i++) {
        if (i != 0) {
            smn[i] = smn[i - 1];
            for (int x : p[i - 1]) {
                smn[i] = max(smn[i], x + 1);
            }
        }
    }

    vector<vector<int>> dp(n, vector<int>(n, -1e18));
    for (int t = 0; t < n; t++) {
        for (int to = 0; to <= t; to++) {
            for (int i = t; i < n; i++) {
                if (smn[i] <= t && t <= smx[i]) {
                    if (i == 0) {
                        dp[i][t] = max(dp[i][t], a[i] + b[i] * t);
                    } else {
                        dp[i][t] = max(dp[i][t], dp[i - 1][to] + a[i] + b[i] * t);
                    }
                }
            }
        }
        if (q[t] != -1) {
            for (int i = 0; i < n; i++) {
                if (i != q[t] - 1) {
                    dp[i][t] = -1e18;
                }
            }
        }
    }

    int ans = -1e18;
    for (int i = 0; i < n; i++) {
        for (int t = mxq; t < n; t++) {
            ans = max(ans, dp[i][t]);
        }
    }

    cout << ans << "\n";
}
