
#include <bits/stdc++.h>

#define all(a) a.begin(), a.end()

#define int long long

using namespace std;

using ll = long long;
using pii = pair<int, int>;

const int inf = 1e9;
const ll INF = 1e16;

const int mod = 998'244'353;

void solve() {
    int n;
    cin >> n;

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

    vector<int> mn(n, 0);
    vector<int> mx(n, +INF);
    int ind = -1;
    int last = -1;
    for (int i = 0, p; i < n; ++i) {
        cin >> p;
        if (p == -1) continue;
        ind = p - 1;
        for (int j = last + 1; j <= ind; ++j) {
            mx[j] = min(mx[j], i);
        }
        last = ind;
        mx[p - 1] = min(mx[p - 1], i);
        if (p != n) mn[p] = max(mn[p], i + 1);
    }

    vector<vector<ll>> dp(n + 1, vector<ll>(2, -INF));
    dp[0][0] = 0;
    dp[0][1] = 0;

    int lst = 0;
    ll ans = (ind == -1 ? 0 : -INF);
    for (int i = 0; i < n; ++i) {
        dp[i + 1][0] = max(dp[i][0] + a[i] + mn[i] * b[i], dp[i][1] + a[i] + max(mn[i], (i == 0 ? - inf : mx[i - 1])) * b[i]);
        dp[i + 1][1] = max(dp[i][1] + a[i] + mx[i] * b[i], dp[i][1] + a[i] + mx[i] * b[i]);

        if (ind <= i) {
            ans = max(ans, max(dp[i + 1][0], dp[i + 1][1]));
        }
    }

    cout << ans << '\n';
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int t = 1;
    //cin >> t;

    while (t--) {
        solve();
    }
}