#include <bits/stdc++.h>

using namespace std;

#define int ll
#define endl '\n'

typedef long long ll;

void solve() {
#ifdef LOCAL
    cout << "___NEW___" << endl;
#endif
    int n;
    cin >> n;
    vector<pair<int, int>> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i].first >> a[i].second;
    }
    vector<int> p(n);
    vector<int> th(n, n);
    int mxxx = 0;
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        mxxx = max(mxxx, p[i]);
        if (p[i] != -1) {
            th[p[i] - 1] = i;
        }
    }
    vector<int> atl(n + 1);
    for (int i = n - 1; i > -1; i--) {
        if (i < n - 1) {
            th[i] = min(th[i], th[i + 1]);
        }
        // if (p[i] == -1) {
        //     p[i] = n;
        // }
        if (p[i] != -1)
            atl[p[i]] = max(atl[p[i]], i + 1);
        th[i] = min(th[i], i);
    }
    vector<int> pref(n + 1);
    for (int i = 0; i < n; i++) {
        pref[i + 1] = pref[i] + a[i].second;
    }
    int ANS = -1e18;
    auto get = [&](int m) {
        int ans = 0;
        int cur = 0;
        vector<int> mnn(m + 1, 1e18);
        if (m > 0) {
            // mnn[m] = pref[m];
            for (int i = m - 1; i > -1; i--) {
                mnn[i] = min(mnn[i + 1], pref[i + 1]);
            }
        }
        for (int i = 0; i < m; i++) {
            int mn = mnn[i] - pref[i];
            // for (int j = i; j < m; j++) {
            //     if (pref[j + 1] - pref[i] < mn) {
            //         mn = pref[j + 1] - pref[i];
            //     }
            // }
            if (mn > 0) {
                cur = th[i];
                // cur = i;
            }
            if (cur < atl[i]) {
                cur = atl[i];
            }
            // ANS = max(ans, ANS);
            ans += a[i].second * cur;
            ans += a[i].first;
        }
        ANS = max(ans, ANS);
        return ans;
    };
    for (int i = mxxx; i < n + 1; i++) {
        get(i);
        // cout << get(i) << ' ';
    }
    // cout << endl;
    // int l = -1, r = n + 1;
    // while (r - l > 2) {
    //     int m = (r + l) / 2;
    //     if (get(m) <= get(m + 1)) {
    //         l = m;
    //     } else {
    //         r = m + 1;
    //     }
    // }
    cout << ANS << endl;
}

signed main() {
#ifdef LOCAL
    freopen("in", "r", stdin);
    freopen("out", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int qwe = 1;
#ifdef LOCAL
    cin >> qwe;
#endif
    for (int _ = 0; _ < qwe; _++) {
        solve();
    }
    return 0;
}