#include "bits/stdc++.h"
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>

// using namespace __gnu_pbds;
// template<class T> 
// using ordered_set = <T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

using namespace std;

#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
using ll = long long;
using ld = long double;

#define int long long

const int inf = 1'000'000'000'000'000'000;

const int mod = 998244353;
const int maxn = 1'000'001;
vector<int> g[maxn];

void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    vector<int> b(n);
    vector<pair<int, int>> bords(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
        cin >> b[i];
        bords[i] = {0, i};
    }

    vector<int> p(n);
    for (int i = 0; i < n; ++i) {
        cin >> p[i];
        if (p[i] != -1) {
            bords[p[i] - 1].second = min(bords[p[i] - 1].second, i);
            if (p[i] < n) {
                bords[p[i]].first = max(bords[p[i]].first, i + 1);
            }
        }
    }

    for (int i = 1; i < n; ++i) {
        bords[i].first = max(bords[i - 1].first, bords[i].first);
    }
    for (int i = n - 2; i >= 0; --i) {
        bords[i].second = min(bords[i].second, bords[i + 1].second);
    }

    int mxp = *max_element(all(p));
    int ans = (mxp < 0 ? 0 : -inf);
    for (int i = 0; i < 10; ++i) {
        int pref = 0;
        int tmp = (mxp < 0 ? 0 : -inf);
        int cnt = i;
        int last_h = 0;
        for (int i = 1; i < n + 1; ++i) {
            if (cnt > 0) {
                pref = pref + a[i - 1] + b[i - 1] * max(last_h, bords[i - 1].first);
                if (i >= mxp) {
                    tmp = max(tmp, pref[i]);
                }
                if (b[i - 1] > 0) {
                    cnt--;
                }
            } else {
                pref = pref + a[i - 1] + b[i - 1] * (b[i - 1] < 0 ? max(last_h, bords[i - 1].first) : bords[i - 1].second);
                if (b[i - 1] > 0) {
                    last_h = max(last_h, bords[i - 1].second);
                }
                if (i >= mxp) {
                    tmp = max(tmp, pref[i]);
                }
            }
        }
        ans = max(ans, tmp);
    }
    cout << ans << '\n';
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    #ifdef LOCAL
    freopen("C:\\Users\\User\\Documents\\olymp\\input.txt", "r", stdin);
    freopen("C:\\Users\\User\\Documents\\olymp\\output.txt", "w", stdout);
    #endif

    int t = 1;
    // cin >> t;
    while (t--) {
        solve();
    }

    return 0;
}