#include <iostream>
#include <vector>

using namespace std;
using ll = long long;

const int mod = 998244353;
const ll inf = 1e18;
const int INF = 1e9;

#define vec vector
#define ff first
#define ss second
#define all(a) a.begin(), a.end()
#define rev reverse
#define umap unordered_map
#define pll pair<ll, ll>
#define pii pair<int, int>
#define len(a) int(a.size())
#define pb push_back


signed main() {
    int n;
    cin >> n;
    vec<pll> a(n);
    for (int i = 0; i < n; i++) cin >> a[i].ff >> a[i].ss;
    vec<int> p(n);
    vec<pll> t(n, { INF, -INF });
    for (ll i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] != -1) {
            p[i]--;
            t[p[i]].ff = min(t[p[i]].ff, i);
            t[p[i]].ss = max(t[p[i]].ss, i);
        }
    }
    vec<ll> dp(n, -inf);
    for (int i = 0; i < n; i++) {
        if (t[i].ff != INF) {
            dp[i] = 0;
            int pos = -1;
            for (int j = i - 1; j >= 0; j--) {
                if (t[j].ff != INF) {
                    pos = j;
                    break;
                }
            }
            ll val = t[i].ff;
            if (pos != -1) dp[i] = dp[pos];
            for (int j = i - 1; j > pos; j--) {
                dp[i] += (a[j].ff + a[j].ss * val);
            }
            dp[i] += a[i].ff + a[i].ss * val;
        }
    }
    int last = -1;
    for (int i = n - 1; i >= 0; i--) {
        if (dp[i] != -inf) {
            last = i;
            break;
        }
    }
    int tm = -1;
    if (last != -1) tm = t[last].ss;
    tm += 1;
    ll mx = 0, cur = 0;
    for (int i = last + 1; i < n; i++) {
        cur += a[i].ff + a[i].ss * i;
        mx = max(mx, cur);
    }
    ll res = 0;
    if (last != -1) res = dp[last];
    cout << res + mx;
}