#include "bits/stdc++.h"

using namespace std;

#ifdef OG_Matveychick1
bool local = 1;
#else
bool local = 0;
#endif


#define ret return
#define con continue
#define be(x) x.begin()
#define en(x) x.end()
#define all(x) be(x), en(x)
#define pb push_back
#define fi first
#define se second
#define ba(x) x.back()
#define pob pop_back
#define for0(i, n) for (ll i = 0; i < n; i++)
#define rfor0(i, n) for (ll i = n - 1; i >= 0; i--)
#define rep(i, a, n) for (ll i = a; i < n; i++)
#define for1(i, n) for (ll i = 1; i < n; i++)
#define rfor1(i, n) for (ll i = n - 1; i >= 1; i--)
#define sz(x) x.size()
#define rev reverse
#define rs resize
#define endl '\n'
typedef long long ll;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
typedef vector<pair<ll, ll> > vpll;
typedef string str;
typedef set<ll> sll;
typedef vector<vector<ll> > vvll;
typedef set<pll> spll;
typedef vector<char> vc;
typedef vector<vector<char> > vvc;
typedef vector<str> vs;
typedef queue<ll> qll;

mt19937_64 rn(chrono::steady_clock::now().time_since_epoch().count());

ll rnd(ll l, ll r) {
    ret rn() % (r - l + 1) + l;
}

void solve();

signed main(int argc, char *argv[]) {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cout.precision(12);
    cout << fixed;
    if (local) {
        freopen("input.txt", "r", stdin);
    }
    ll t = 1;
    // cin >> t;
    while (t--) {
        solve();
    }
}


const ll N = 1e6 + 5;

ll n, a[N], b[N], p[N], mn[N], mx[N], lst, d[N];

void solve() {
    cin >> n;
    for0(i, n) cin >> a[i] >> b[i], mn[i] = i;
    for0(i, n) cin >> p[i];
    rfor0(i, n) {
        if (p[i] != -1) {
            mn[p[i] - 1] = i;
        }
    }
    for0(i, n) {
        if (p[i] != -1) {
            mx[p[i]] = i + 1;
            lst = p[i];
        }
    }
    rfor0(i, n - 1) mn[i] = min(mn[i], mn[i + 1]);
    for1(i, n) mx[i] = max(mx[i], mx[i - 1]);
    ll ans = (lst == 0 ? 0ll : -1e18);
    ll l = 0, r = 0, cl = 0;
    for0(i, n) {
        ll nl = mx[i], nr = mn[i];
        while (r != nr) {
            d[r] = 0;
            r++;
        }
        while (l != nl) {
            cl += d[l];
            l++;
        }
        cl += a[i] + b[i] * l;
        rep(j, l, r) d[j] += b[i];
        rep(j, l, r) d[j] = max(0ll, d[j]);
        if (i >= lst - 1) {
            ans = max(ans, cl);
            ll cf = cl;
            rep(j, l, r) cf += d[j], ans = max(ans, cf);
        }
    }
    cout << ans;
}
