#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

void fast_in_out() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << setprecision(18) << fixed;
#ifdef LOCAL
    freopen("input.txt", "r",stdin);
    freopen("output.txt", "w",stdout);
#endif
}

typedef tree<int, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
#define all(x) (x).begin(), (x).end()
#define int long long
using ll = long long;
const int N = 5e3, inf = 1e16;
int a[N], b[N], p[N], c[N + 1], d[N + 1];
int dp[N + 1][N], n, ans = -inf;

void solve() {
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> a[i] >> b[i];
    }
    for (int i = 0; i <= n; ++i) {
        d[i] = i;
    }
    int pos = -1;
    for (int i = 0; i < n; ++i) {
        cin >> p[i];
        if (p[i] != -1) {
            d[p[i] - 1] = min(d[p[i] - 1], i);
            pos = max(pos, p[i] - 1);
            c[p[i]] = max(c[p[i]], i + 1);
        }
    }
    for (int i = 1; i < n; ++i) {
        c[i] = max(c[i], c[i - 1]);
    }
    for (int i = n - 2; i >= 0; --i) {
        d[i] = min(d[i], d[i + 1]);
    }
    if (pos == -1) {
        ans = 0;
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j <= n - 1; ++j) {
            dp[i + 1][j] = -inf;
            if (c[i] <= j && j <= d[i]) {
                if (dp[i][j] != -inf)
                    dp[i + 1][j] = dp[i][j] + a[i] + b[i] * j;
            }
            if (j >= 1)
                dp[i + 1][j] = max(dp[i + 1][j], dp[i + 1][j - 1]);
        }
        if (i >= pos) {
            ans = max(ans, dp[i + 1][n - 1]);
        }
    }
    cout << ans;
}

signed main() {
    fast_in_out();
    int qwe = 1;
    // cin >> qwe;
    while (qwe--) {
        solve();
    }
}
