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

using namespace std;

#define ff first
#define ss second
#define rs resize
#define pb push_back
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define int long long

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef long double ld;

template<typename T, typename T1>
istream& operator >>(istream &in, pair<T, T1> &a) {
    in >> a.ff >> a.ss;
    return in;
}

template<typename T, typename T1>
ostream& operator <<(ostream &out, pair<T, T1> &a) {
    out << a.ff << " " << a.ss;
    return out;
}

template<typename T>
istream& operator >>(istream &in, vector<T> &a) {
    for (auto &i : a) in >> i;
    return in;
}

template<typename T>
ostream& operator <<(ostream &out, vector<T> &a) {
    for (auto i : a) out << i << " ";
    return out;
}

const int maxn = 1e6 + 10;

pii s[maxn], t[maxn];
int p[maxn], used[maxn];
//vector<int> dp[maxn];
int dp[maxn];
void solve() {
    int n; cin >> n;
    for (int i = 0; i < n; i++) cin >> s[i];
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        if (p[i] != -1) p[i]--;
    }

    for (int i = 0; i < n; i++) t[i].ss = i;
    for (int i = 0; i < n; i++) {
        if (p[i] == -1) continue;
        used[p[i]] = 1;
        t[p[i]].ss = min(t[p[i]].ss, i);
        t[p[i] + 1].ff = max(t[p[i] + 1].ff, i + 1);
    }
    // for (int i = 0; i < n; i++) {
    //     cout << t[i] << "\n";
    // }
    // cout << "\n";
    for (int i = 1; i < n; i++) {
        t[i].ff = max(t[i].ff, t[i - 1].ff);
    }
    for (int i = n - 2; i > -1; i--) {
        t[i].ss = min(t[i].ss, t[i + 1].ss);
    }

    // for (int i = 0; i < n; i++) {
    //     cout << t[i] << "\n";
    // }

    // for (int i = 0; i < n; i++) {
    //     dp[i].assign(t[i].ss + 1, -1e18);
    //     for (int j = t[i].ff; j <= t[i].ss; j++) {
    //         dp[i][j] = s[i].ff + s[i].ss * j;
    //         if (i != 0) dp[i][j] += (j < sz(dp[i - 1]) ? dp[i - 1][j] : dp[i - 1].back());
    //
    //         if (j !=0) dp[i][j] = max(dp[i][j], dp[i][j - 1]);
    //     }
    // }

    for (int i = 0; i < n; i++) {
        if (s[i].ss < 0) dp[i] = s[i].ff + s[i].ss * t[i].ff;
        if (s[i].ss >= 0) dp[i] = s[i].ff + s[i].ss * t[i].ss;
        if (i != -1) dp[i] += dp[i - 1];
    }

    int ans = -1e18;
    for (int i = n - 1; i > -1; i--) {
        //cout << dp[i] << "\n";
        ans = max(ans, dp[i]);
        if (used[i]) break;
        if (i == 0) ans = max(ans, 0LL);
    }
    cout << ans << "\n";
}

int32_t main() {
#ifdef LOCAL
    ios_base::sync_with_stdio(0);
    cin.tie(0);
#endif
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
#endif

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