#include<bits/stdc++.h>

using namespace std;

#define int long long

const int INF = 3e18;

signed main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    int n;
    cin >> n;
    vector<pair<int, int>> el(n);
    for (int i = 0; i < n; i++) {
        cin >> el[i].first >> el[i].second;
    }
    vector<int> p(n), mnt(n), curp(n + 1), mx(n, INF);
    int mxp = 0;
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] != -1) {
            curp[p[i]] = max(curp[p[i]], i + 1);
            mx[p[i] - 1] = min(mx[p[i] - 1], i + 1);
            mxp = max(mxp, p[i]);
        }
    }
    vector<int> mx1(n + 1, INF);
    for (int i = n - 1; i >= 0; i--) {
        mx1[i] = mx1[i + 1];
        mx1[i] = min(mx1[i], mx[i]);
    }
    // for (auto u : mx1) {
    //     cout << u << ' ';
    // }
    // cout << '\n';
    int nowmx = 0;
    for (int i = 0; i < n; i++) {
        nowmx = max(nowmx, curp[i]);
        mnt[i] = nowmx;
    }
    vector<int> bps(n + 1);
    for (int i = 1; i <= n; i++) {
        bps[i] = bps[i - 1] + el[i - 1].second;
    }
    int ans = 0, cur = 0, delta = 0, sall = 0;
    set<int> ids;
    multiset<pair<int, int>> val;
    vector<int> sum(n);
    for (int i = 0; i < n; i++) {
        if (!i || el[i].second > 0) {
            sum.assign(n, 0);
            sall = 0;
            for (int j = 0; j <= i; j++) {
                sall += el[j].second;
            }
            sum[i] = el[i].second;
            for (int j = i - 1; j >= 0; j--) {
                sum[j] = sum[j + 1] + el[j].second;
            }
            val.clear();
            ids.clear();
            for (int j = 0; j <= i; j++) {
                val.insert({sum[j], j});
                ids.insert(j);
            }
            cur = 0;
            for (int j = 0; j <= i; j++) {
                cur += el[j].first;
                cur += el[j].second * j;
            }
            delta = 0;
        } else {
            delta += el[i].second;
            ids.insert(i);
            val.insert({el[i].second - delta, i});
            cur += el[i].first + el[i].second * i;
        }
        while (!val.empty() && (*val.begin()).first + delta < 0) {
            auto [vl, id] = *val.begin();
            val.erase(val.begin());
            auto it = ids.lower_bound(id);
            int pvl = 0, svl = 0;
            if (it != ids.begin()) {
                auto it1 = it;
                it1--;
                pvl = id - *it1;
            }
            auto it1 = it;
            it1++;
            if (it1 != ids.end()) {
                svl = bps[*it1] - bps[id];
            } else {
                svl = bps[i + 1] - bps[id];
            }
            cur -= pvl * svl;
            ids.erase(id);
        }
        ans = max(ans, cur);
    }
    cout << ans << '\n';
}