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

#pragma GCC optimize("O3", "unroll-loops")

// #define FILE
#define int long long

const int INF = 1e18;

signed main() {
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifdef FILE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    int n; cin >> n;
    vector<int> a(n + 1), b(n + 1);
    for (int i = 1; i <= n; ++i) {
        cin >> a[i] >> b[i];
    }
    vector<int> p(n + 1);
    vector<int> mx(n + 1, n - 1), mn(n + 1, 0);
    for (int i = 1; i <= n; ++i) {
        mx[i] = i - 1;
    }
    for (int i = 1; i <= n; ++i) {
        cin >> p[i];
        if (p[i] != -1) {
            mx[p[i]] = min(mx[p[i]], i - 1);
            if (p[i] + 1 <= n) mn[p[i] + 1] = max(mn[p[i] + 1], i);
        }
    }
    for (int i = 2; i <= n; ++i) {
        mn[i] = max(mn[i], mn[i - 1]);
    }
    for (int i = n - 1; i >= 1; --i) {
        mx[i] = min(mx[i], mx[i + 1]);
    }
    // for (int i = 1; i <= n; ++i) {
    //     cout << mn[i] << ' ' << mx[i] << endl;
    // }
    vector<vector<int>> dp(n + 1, vector<int>(n, -INF));
    vector<vector<int>> pref(n + 1, vector<int>(n, -INF));
    dp[0][0] = 0;
    pref[0][0] = 0;
    for (int t = 1; t < n; ++t) {
        pref[0][t] = max(dp[0][t], pref[0][t - 1]);
    }
    int ans = -INF;
    for (int i = 1; i <= n; ++i) {
        for (int t = mn[i]; t <= mx[i]; ++t) {
            dp[i][t] = a[i] + t * b[i] + pref[i - 1][t];
            // cout << i << " " << t << " : " << dp[i][t] << endl;
            ans = max(ans, dp[i][t]);
        }
        // cout << endl;
        pref[i][0] = dp[i][0];
        for (int t = 1; t < n; ++t) {
            pref[i][t] = max(dp[i][t], pref[i][t - 1]);
        }
    }
    cout << ans;
}