#include<bits/stdc++.h>
using namespace std;

#define ff first
#define ss second
using ll = long long;
using ld = long double;

#define int long long
const int maxn = 5e3 + 2;
const int inf = 1e18 + 1;

int a[maxn], b[maxn];

int p[maxn];

int dp[maxn][maxn];

int pref[maxn][maxn];

int l[maxn], r[maxn];

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n; cin >> n;
    for (int i = 1; i < n + 1; i++) {
        cin >> a[i] >> b[i];
        r[i] = n;
    }
    int mx = 0;
    for (int i = 1; i < n + 1; i++) {
        cin >> p[i];
        if (p[i] == -1) {
            continue;
        }
        l[p[i] + 1] = i;
        r[p[i]] = i - 1;
        mx = max(mx, p[i]);
    }
    for (int i = 1; i < n + 1; i++) {
        for (int j = 0; j < n + 1; j++) {
            dp[i][j] = pref[i - 1][j] + a[i] + b[i] * j;
        }
        for (int j = 0; j < l[i]; j++) {
            dp[i][j] = -inf;
        }
        for (int j = min(i, r[i] + 1); j < n + 1; j++) {
            dp[i][j] = -inf;
        }
        pref[i][0] = dp[i][0];
        for (int j = 1; j < n + 1; j++) {
            pref[i][j] = max(pref[i][j - 1], dp[i][j]);
        }
    }
    int res = -inf;
    for (int i = mx; i < n + 1; i++) {
        for (int j = 0; j < n + 1; j++) {
            res = max(res, dp[i][j]);
        }
    }
    cout << res << "\n";
}
