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

#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx")

#define int long long
#define all(a) a.begin(), a.end()

const int N = 5001;
int dp[N][N];

void solve() {
    int n;
    cin >> n;
    vector<int> a(n+1), b(n+1), p(n+1);
    for (int i = 1; i <= n; ++i) {
        cin >> a[i] >> b[i];
    }
    for (int i = 1; i <= n; ++i) {
        cin >> p[i];
    }
    vector<vector<int>> dp(n+1, vector<int> (n+1, -1e18));
    dp[0][0] = 0;
    for (int t = 1; t <= n; ++t) {
        if (p[t] != -1) {
            dp[t][0] = dp[t-1][0];
            for (int c = 1; c <= n; ++c) {
                dp[t][c] = dp[t-1][c];
                if (c >= t) {
                    dp[t][c] = max(dp[t][c], dp[t][c-1] + a[c] + b[c] * (t-1));
                }
            }
            for (int i = 0; i <= n; ++i) {
                if (i != p[t]) {
                    dp[t][i] = -1e18;
                }
            }
        }else {
            dp[t][0] = 0;
            for (int c = 1; c <= n; ++c) {
                dp[t][c] = dp[t-1][c];
                if (c >= t) {
                    dp[t][c] = max(dp[t][c], dp[t][c-1] + a[c] + b[c] * (t-1));
                }
            }
        }
    }
    int ans = -1e18;
    for (int c = 1; c <= n; ++c) {
        ans = max(ans, dp[n][c]);
    }
    cout << ans;
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int tt = 1;
    //cin >> tt;
    while (tt--) {
        solve();
        cout << '\n';
    }
}