#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

using namespace std;
using namespace __gnu_pbds;

using ll = long long;
#define int long long
const int MOD = 998244353;
const int INF = 1e18;

using ordered_set = tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>;

void solve1();

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

void solve1() {
    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i] >> b[i];
    }
    vector<int> p(n);
    for (int i = 0; i < n; i++) {
        cin >> p[i];
    }
    vector<int> mx_time(n);
    vector<int> mn_time(n);
    for (int i = 0; i < n; i++) {
        mx_time[i] = i;
    }
    for (int i = 0; i < n; i++) {
        if (p[i] == -1) continue;
        mx_time[p[i] - 1] = min(mx_time[p[i] - 1], i);
        if (p[i] != n) {
            mn_time[p[i]] = max(mn_time[p[i]], i + 1);
        }
    }
    vector<vector<int> > dp(n, vector<int>(n, -INF));
    int ans = -INF;
    for (int i = 0; i < n; i++) {
        if (i == 0) {
            for (int j = 0; j <= mx_time[i]; j++) {
                dp[i][j] = a[i] + j * b[i];
                ans = max(ans, dp[i][j]);
            }
        } else {
            int mx = -INF;
            for (int j = 0; j < mn_time[i]; j++) {
                mx = max(mx, dp[i - 1][j]);
            }
            for (int j = mn_time[i]; j <= mx_time[i]; j++) {
                mx = max(mx, dp[i - 1][j]);
                dp[i][j] = max(dp[i][j], mx + a[i] + j * b[i]);
                ans = max(ans, dp[i][j]);
            }
        }
    }
    if (ans == -INF) exit(-1);
    cout << ans;
}
