#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> oset;
using ll = long long;
mt19937 rnd(52);
ll mod = 998244353;
int main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#else
    cin.tie(nullptr);
    ios::sync_with_stdio(0);
#endif
    int n;
    cin >> n;
    vector<ll> a(n);
    vector<ll> b(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i] >> b[i];
    }
    vector<ll> prefsa(n+1);
    vector<ll> prefsb(n+1);
    for (int i = 0; i < n; i++) {
        prefsa[i+1] = prefsa[i] + a[i];
        prefsb[i+1] = prefsb[i] + b[i];
    }
    vector<int> p(n);
    vector<int> mi(n, 1e9);
    vector<int> ma(n, -1);
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] == -1) {
            continue;
        }
        p[i]--;
        mi[p[i]] = min(mi[p[i]], i);
        ma[p[i]] = max(ma[p[i]], i);
    }
    vector<ll> dp(n+1, -1e18);
    dp[0] = 0;
    vector<pair<ll, ll>> lines;
    ll sum = 0;
    ll ans = -1e18;
    /*for (auto x:mi) {
        cout << x << ' ';
    }
    cout << '\n';*/
    for (int i = 1; i <= n; i++) {
        ll con = dp[i-1] - prefsb[i-1]*min(i-1, mi[i-1]);
        lines.push_back({con, min(mi[i-1], i-1)});
        //cout << i << ": " << con << ' ' << min(mi[i-1], i-1) << endl;
        for (auto [b, k] : lines) {
            /*if (mi[i-1]!=1e9 and k > mi[i-1]) {
                cout << "SKIP\n";
                continue;
            }*/
            //cout << i << ' ' << b << ' ' << k << endl;
            dp[i] = max(dp[i], b + prefsb[i]*k);
        }
        vector<pair<ll, ll>> new_lines;
        for (auto [b, k] : lines) {
            /*if (ma[i-1]!=-1 and k-1 <= ma[i-1]) {
                cout << "DEL " << b << ' ' << k << endl;
                continue;
            }*/
            new_lines.push_back({b, k});
        }
        lines = new_lines;
        sum+=a[i-1];
        //cout << dp[i] << "Dp" << endl;
        /*if (mi[i-1]!=1e9) {
            ans = dp[i]+sum;
        } else {*/
            ans = max(ans, dp[i]+sum);
        //}
    }
    cout << ans;
    return 0;
}