#include<bits/stdc++.h>
using namespace std;
// #pragma GCC optimize("Ofast")
using ll = long long;
using ld = long double;
using vl = __int128_t;
using ull = unsigned long long;
#define pb emplace_back
#define all(x) (x).begin(), (x).end()
constexpr int mod = 998244353;
#define int long long
const int INF = 1e18;
void solve() {
    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i] >> b[i];
    }
    vector<int> p(n);
    for (int &i : p) cin >> i;
    vector<int>mn(n, 0);
    vector<int>max_(n);
    for (int i = 0; i < n; ++i) {
        max_[i] = i;
    }
    for (int i = 0; i < n; ++i) {
        if (p[i] == -1) continue;
        max_[p[i] - 1] = min(max_[p[i] - 1], i);
    }
    ll ans = -INF;
    /*
    vector<vector<int>> dp(n, vector<int> (n, -INF));
    dp[0][0] = a[0];
    for (int i = 1; i < n; ++i) {
        ll mx = -INF;
        for (int t = mn[i]; t <= max_[i]; ++t) {
            //mx = max(mx, dp[i - 1][t]);
            for (int k = 0; k <= t; ++k) {
                dp[i][t] = max(dp[i][t], dp[i - 1][k] + a[i] + t * b[i]);
                ans = max(ans, dp[i][t]);
            }
        }
    }
    */
    /*
    ll mx = *max_element(all(p));
    ll ans = 0;
    ll sum = 0;
    for (int i = 0; i < n; ++i) {
        sum += a[i];
        if (i + 1 >= mx) ans = max(ans, sum);
    }*/
    ll sum = 0;
    int mx = *max_element(all(p));
    for (int i = 0; i < n; ++i) {
        sum += a[i] + b[i] * max_[i];
        if (i + 1 >= mx) ans = max(ans, sum);
    }
    cout << ans;
}
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    // cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}
