#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

#define cin(x) for (auto &i : (x)) cin >> i;
#define cout(x) for (auto &i : (x)) cout << i << " "; cout << "\n"
#define fori(x) for (int i = 0; i<(x); i++)
#define forj(x) for (int j = 0; j<(x); j++)
#define fork(x) for (int k = 0; k<(x); k++)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(), (x).rend()

mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
template<class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

long long get(int l, int r, vector<long long> &a) {
    long long re = a[r];
    if (l != 0) re -= a[l - 1];
    return re;
}

void solve() {
    int n;
    cin >> n;
    vector<long long> a(n), b(n);
    fori(n) {
        cin >> a[i] >> b[i];
    }
    fori(n-1) b[i + 1] += b[i];
    vector<int> p(n);
    cin(p);
    vector<vector<long long> > dp(n, vector<long long>(n + 1, -1e17));
    fori(n) {
        for (int j = 1; j <= n; j++) {
            if (p[i] != -1 && j != p[i]) continue;
            // have taken j
            for (int c = 0; c <= j; c++) {
                if (i != 0) {
                    dp[i][j] = max(dp[i][j], dp[i - 1][j - c] + i * get(j - c, j - 1, b));
                } else {
                    dp[i][j] = max(dp[i][j], i * get(j - c, j - 1, b));
                }
            }
        }
    }
    long long ans = -1e17;
    fori(n+1) {
        ans = max(ans, dp[n - 1][i]);
    }
    ans += accumulate(all(a), 0ll);
    cout << ans;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int tt = 1;
    // cin >> tt;
    while (tt--) {
        solve();
    }
    return 0;
}
