#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using ld = long double;

const int mod = 1e9 + 7;
const int maxn = 2e5 + 1;

void solve() {
    int n; cin >> n;

    vector<ll> a(n), b(n);
    for (int i{}; i < n; i++) {
        cin >> a[i] >> b[i];
    }

    vector<int> p(n);
    for (int i{}; i < n; i++) cin >> p[i];


    vector<int> l(n), r(n, n);

    for (int i{}; i < n; i++) {
        if (p[i] == -1) continue;
        r[p[i] - 1] = i;
        for (int j = p[i]; j < n; j++) {
            l[j] = i;
        }
    }

    ll ans = a[0];
    vector<vector<ll>> dp(n, vector<ll> (n));
    ll pref = a[0];
    dp[0][0] = 0;
    for (int i = 1; i < n; i++) {
        pref += a[i];
        ll bst = dp[i - 1][l[i]];
        for (int j = l[i]; j <= min(i, r[i]); j++) {
            if (j < i) bst = max(bst, dp[i - 1][j]);
            dp[i][j] = bst + b[i] * j;

            ans = max(ans, dp[i][j] + pref);
        }
    }

    cout << ans;
}

signed main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int it = 1;

    //cin >> it;

    while (it--) {
        solve();
    }
}