#include <bits/stdc++.h>

using namespace std;

#define int long long

const int inf = 1e18;

signed main() {
    #ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    vector<int> a(n), b(n), p(n);
    for (int i = 0; i < n; ++i) cin >> a[i] >> b[i];
    for (int i = 0; i < n; ++i) cin >> p[i];
    vector<int> t(n);
    for (int i = 0; i < n; ++i) t[i] = i;
    for (int i = 0; i < n; ++i) {
        if (p[i] != -1) t[p[i] - 1] = min(t[p[i] - 1], i);
    }
    vector<vector<int>> dp(n, vector<int> (n + 1, -inf));
    for (int j = 0; j <= t[0]; ++j) dp[0][j] = a[j] + j * b[j];
    for (int i = 1; i < n; ++i) {
        int mx = -inf;
        for (int j = 0; j <= t[i]; ++j) {
            mx = max(mx, dp[i - 1][j]);
            dp[i][j] = mx + a[i] + j * b[i];
        }
        for (int j = 0; j <= n; ++j) mx = max(mx, dp[i - 1][j]);
        dp[i][n] = mx;
    }
    // for (int i : t) cout << i << ' ';
    // cout << endl << endl;
    // for (auto i : dp) {
    //     for (int j : i) {
    //         if (j == -inf) cout << "-inf ";
    //         else cout << j << ' ';
    //     }
    //     cout << endl;
    // }
    // cout << endl;
    int ans = -inf;
    for (int j = 0; j <= n; ++j) ans = max(ans, dp.back()[j]);
    cout << ans;
}