#include <bits/stdc++.h>

#define int long long

using namespace std;
using ll = long long;
using ld = long double;
using sll = __int128;

const int maxn = 1e6, inf = 1e16;

int a[maxn], b[maxn];

void solve() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i] >> b[i];
    }
    vector<int> p(n + 1);
    vector<int> mn(n + 1, 1);
    vector<int> mx(n + 1);
    vector<int> pref(n + 1);
    int lst = 1;
    for (int i = 1; i <= n; i++) mx[i] = i - 1;
    for (int i = 1; i <= n; i++) {
        cin >> p[i];
        if (p[i] != -1) mx[p[i]] = i - 1;
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) pref[i] = pref[i - 1] + b[i] * mx[i];
    int sm = 0;
    for (int i = 1; i <= n; i++) {
        sm += a[i];
        ans = max(ans, pref[i] + sm);
    }
    cout << ans;
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int test = 1;
    // cin >> test;
    while (test--) {
        solve();
    }
}