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


#define int long long
#define line cout << "\n"
#define pb push_back
#define ppb pop_back
#define pf push_front
#define ppf pop_front
#define sz(a) (int) a.size()
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define pii pair<int, int>

typedef string str;
typedef long long ll;
typedef long double ld;


void solve() {
    int n;
    cin >> n;
    vector<pii> a(n + 1);
    for (int i = 1; i <= n; i++) {
        cin >> a[i].first >> a[i].second;
    }
    vector<int> p(n + 1);
    vector<int> lim(n + 1);
    for (int i = 0; i <= n; i++) {
        lim[i] = i - 1;
    }
    int mi = 0;
    vector<int> lim_down(n + 1);
    for (int i = 1; i <= n; i++) {
        cin >> p[i];
        mi = max(mi, p[i]);
        if (p[i] == -1) {
            continue;
        }
        lim[p[i]] = min(lim[p[i]], i - 1);
        lim_down[p[i] + 1] = i;
    }
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1e18));
    dp[0][0] = 0;
    for (int i = 1; i <= n; i++) {
        int ma = -1e18;
        for (int tj = 0; tj < lim_down[i]; tj++) {
            ma = max(ma, dp[i - 1][tj]);
        }
        for (int tj = lim_down[i]; tj <= lim[i]; tj++) {
            ma = max(ma, dp[i - 1][tj]);
            dp[i][tj] = ma + a[i].first + a[i].second * tj;
        }
    }
    int ans = -1e18;
    for (int i = mi; i <= n; i++) {
        ans = max(ans, *max_element(all(dp[i])));
    }
    cout << ans; line;
}


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


#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int t = 1;
    // cin >> t;
    while (t--) {
        solve();
    }
}