#include<bits/stdc++.h>
//#include<bits/extc++.h>
//using namespace __gnu_pbds;
using namespace std;
using ll = long long;
//using oset = tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>;


/*
struct segtree{
    vector<ll> tree;
    ll sz;
    ll def = 0;
    ll merg(ll a, ll b) {
        return a + b;
    }
    void clar(ll n) {
        tree.assign(4 * n, def);
        sz = n;
    }
    segtree() {

    }
    void build(ll v, ll l, ll r, vector<ll> & a) {
        if (r - l == 1) {
            tree[v] = a[l];
            return;
        }
        ll m = (l + r) / 2;
        build(v * 2 + 1, l, m, a);
        build(v * 2 + 2, m, r, a);
        tree[v] = merg(tree[v * 2 + 1], tree[v * 2 + 2]);
    }
    segtree(vector<ll> & a) {
        ll n = (ll)a.size();
        clar(n);
        build(0, 0, sz, a);
    }
};
*/

ll mod = 998244353;

ll po(ll x, ll n) {
    if (n == 0) {
        return 1;
    }
    if (n % 2 == 0) {
        ll c = po(x, n / 2);
        return (c * c) % mod;
    } else {
        return (x * po(x, n - 1)) % mod;
    }
}



void solve() {
    ll n;
    cin >> n;
    vector<pair<ll, ll>> a(n);
    for (ll i = 0; i < n; i++) {
        cin >> a[i].first >> a[i].second;
    }
    vector<ll> p(n);
    vector<ll> vsp(n, 0);
    vector<ll> tr(n);
    for (ll i = 0; i < n; i++) {
        tr[i] = i;
    }
    ll m = -1;
    for (ll i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] != -1) {
            vsp[p[i]] = max(vsp[p[i]], i);
            p[i]--;
            m = max(m, p[i]);
            tr[p[i]] = min(tr[p[i]], i);
        }
    }
    vector<ll> tl(n);
    ll ma1 = 0;
    for (ll i = 0; i < n; i++) {
        tl[i] = ma1;
        ma1 = max(ma1, vsp[i]);
    }
    vector<vector<ll>> dp(n, vector<ll> (n, -1e18));
    dp[0][0] = a[0].first;
    for (ll i = 1; i < n; i++) {
        ll ma = -1e18;
        for (ll j = tl[i]; j <= tr[i]; j++) {
            if (j <= i - 1) {
                ma = max(ma, dp[i - 1][j]);
            }
            dp[i][j] = max(dp[i][j], ma + a[i].first + a[i].second * j);
        }
    }
    ll ans = -1e18;
    if (m == -1) {
        ans = 0;
        for (auto & i : dp) {
            for (auto & j : i) {
                ans = max(ans, j);
            }
        }
    } else {
        for (ll i = m; i < n; i++) {
            for (auto j : dp[i]) {
                ans = max(ans, j);
            }
        }
    }
    cout << ans << endl;
}

signed main() {
    int MULTITEST = 0;
    #ifdef zapvm
        MULTITEST = 1;
        freopen("in.txt", "r", stdin);
    #endif
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    if (MULTITEST) {
        cin >> t;
    }
    while (t--) {
        solve();
    }
}