#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using ld = long double;
using ull = unsigned long long;
using i128 = __int128_t;

const ll inf = 1e18 + 1e16;
const ll inf_t = 1e9 + 7;
const ll mod = 998244353;

#define int ll

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> p(n + 1);
    for (int i = 0; i < n; ++i) cin >> p[i];
    p[n] = n;

    vector <int> last(n);
    iota(last.begin(), last.end(), 0);

    last[0] = max(p[0], 0ll);
    vector <int> rp(n);
    iota(rp.begin(), rp.end(), 0);
    for (int i = 0; i < n; ++i) {
        if (p[i] != -1) rp[p[i] - 1] = min(rp[i], i - 1);
    }
    for (int i = n - 2; i >= 0; --i) {
        rp[i] = min(rp[i], rp[i + 1]);
    }
    for (int i = 0; i < n; ++i) {
        last[i] = min({last[i], rp[i]});
    }

    int ans = 0;
    int answer = -inf;
    for (int i = 0; i < n; ++i) {
        ans += a[i] + last[i] * b[i];
        answer = max(ans, answer);
    }

    cout << answer << "\n";
}

signed main() {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

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