#include<bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,popcnt")
#define int long long
using oset = tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>;
int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    vector<array<int,2>> a(n + 1);
    for (int i = 1; i <= n; ++i) cin >> a[i][0] >> a[i][1];
    vector<int> p(n + 1);
    vector<int> t(n + 1),h(n + 2);
    for (int i = 0; i <= n; ++i) {
        t[i] = i;
    }
    int km = 0;
    for (int i = 1; i <= n; ++i) {
        cin >> p[i];
        km = max(km,p[i]);
        if (p[i] !=-1) {
            t[p[i]] = min(t[p[i]],i);
            h[p[i] + 1] = max(h[p[i] + 1],i);
        }
    }

    vector<vector<int>> dp(n + 1,vector<int> (n + 1,-1e18));
    for (int j = 0; j <=n; ++j) dp[0][j] = 0;
    for (int i = 1; i <= n; ++i) {
        for (int j = h[i];j < t[i]; ++j) {
            for (int k = 0; k <=j; ++k) {
                dp[i][j] = max(dp[i][j],dp[i-1][k] + a[i][0] + a[i][1] * j);
            }
        }
    }
    int ans = -1e18;
    for (int i = km; i <=n; ++i) {
        for (int j = h[i];j <=t[i]; ++j) {
            ans = max(ans,dp[i][j]);
        }
    }
    cout << ans << '\n';
}