#include <bits/stdc++.h>
using  namespace std;
#define all(x) x.begin(), x.end()
using ll = long long;
using sll = __int128;
using ld = long double;
const ll inf = 1e18;
void solve() {
    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<vector<ll>> dp(n + 1, vector<ll>(n + 1, -inf));
    ll ans = -inf;
    for (int i = 1; i <= n; ++i) cin >> p[i];
    vector<int> l(n + 1, n + 1), r(n + 1, 0);
    for (int i = 1; i <= n; ++i) {
        if (p[i] != -1) l[p[i]] = min(i, l[p[i]]);
        if (p[i] != -1) r[p[i] + 1] = max(i, r[p[i]]);
    }
    for (int i = n - 1; i >= 1; --i) {
        l[i] = min(l[i], l[i + 1]);
    }
    for (int i = 2; i <= n; ++i) {
        r[i] = max(r[i], r[i - 1]);
    }
    dp[0][0] = 0;
    for (int i = 1; i <= n; ++i) {
        ll cur = dp[i - 1][0];
        for (int j = r[i]; j < min(l[i], i); ++j) {
            cur = max(cur, dp[i - 1][j]);
            dp[i][j] = max(dp[i][j], cur + a[i] + (ll)b[i] * j);
            ans = max(ans, dp[i][j]);
        }
    }
    cout << ans;

}
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int t = 1;
    //cin >> t;
    while (t--) {
        solve();
    }
}