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

#ifndef LOCAL
#pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2")
#endif

signed main() {
    ios_base::sync_with_stdio(NULL);
    cin.tie(NULL);
#ifdef LOCAL
    freopen("./../input.txt", "r", stdin);
#endif
    int n;
    cin >> n;
    vector<pair<int, int>> a(n);
    vector<int> p(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i].first >> a[i].second;
    }
    vector<int> ql(n, 0), qr(n, n - 1);
    int mxp = 0;
    for (int i = 0; i < n; i++) {
        qr[i] = i;
    }
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] != -1) {
            qr[p[i] - 1] = i;
            if (p[i] != n)
                ql[p[i]] = i + 1;

            mxp = p[i];
        }
    }
    for (int i = 1; i < n; i++) {
        ql[i] = max(ql[i - 1], ql[i]);
    }
    for (int i = n - 2; i >= 0; i--) {
        qr[i] = min(qr[i + 1], qr[i]);
    }
    vector<vector<int>> dp(n + 1, vector<int>(n, -1e18));
    dp[0][0] = 0;
    int ans = -1e18;
    for (int i = 0; i < n; i++) {
        int mx = -1e18;
        int l = ql[i], r = qr[i];
        for (int j = 0; j < l; j++) {
            mx = max(mx, dp[i][j]);
        }
        for (int j = l; j <= r; j++) {
            mx = max(mx, dp[i][j]);
            dp[i + 1][j] = max(dp[i + 1][j], mx + a[i].first + j * a[i].second);
        }
    }
    for (int i = mxp; i <= n; i++) {
        for (int j = 0; j < n; j++) {
            ans = max(ans, dp[i][j]);
        }
    }
    cout << ans << endl;
    return 0;
}