#include <bits/stdc++.h>
using namespace  std;
#define int long long
const int INF = 1e18;
const int mod = 998244353;
vector <int> give_obr(vector <int> vec) {
    vector <int> ans(vec.size());
    for (int i = 0;i < vec.size();i++) {
        ans[vec[i]] = i;
    }
    return ans;
}
int binpow(int a,int b) {
    if (!b)return 1;
    if (b%2==0) {
        int mid = binpow(a,b/2);
        return (mid * mid) % mod;
    }
    return (a * binpow(a,b-1) )% mod;
}
int give_sum(vector <int> &vec) {
    int n = vec.size();
    int ans = 0;
    for (int i = 0;i < n;i++) {
        ans += binpow(vec[i]+1,i+1);
        if (ans >= mod) {
            ans-=mod;
        }
    }
    return ans;
}
void sub_solve(int n,int q) {
    vector <int> vec(n);
    for (int i =0;i < n;i++) {
        cin >> vec[i];
        vec[i]--;
    }
    int mask = (1<<3);
    vector <int> var_ans(mask);
    vector <int> all_zap(q);
    for (int i = 0;i < q;i++) {
        cin >> all_zap[i];
    }
    for (auto el : all_zap) {
        vector <int> tmp = vec;
        if (el == 2) {
            for (int i = 0;i < n;i++) {
                tmp[i] = n - vec[i] - 1;
            }
        }
        if (el == 1) {
            for (int i = 0;i < n;i++) {
                tmp[i] = vec[n-i-1];
            }
        }
        if (el == 3) {
            for (int i = 0;i < n;i++) {
                tmp[vec[i]] = i;
            }
        }
        vec = tmp;
        cout << give_sum(vec) << " ";

    }
}
signed main() {
    int n;
    cin >> n;
    vector <pair<int,int>> vec(n);
    for (int i = 0;i < n;i++) {
        cin >> vec[i].first >> vec[i].second;
    }
    vector <int> pi(n);
    int min_sz = 0;
    for (int i  =0;i < n;i++) {
        cin >> pi[i];
        min_sz = max(min_sz,pi[i]);
    }
    vector <int> l(n),r(n,n-1);
    int f_free = 0;
    int last_pi = 0;
    for (int i = 0;i < n;i++) {
        r[i] = min(r[i],i);
           if (pi[i] != -1) {
               if (pi[i] < n) {
                   l[pi[i]] = max(l[pi[i]],i+1);
               }
               if (pi[i] - 1 >= 0) {
                   r[pi[i]-1] = min(r[pi[i]-1],i);
               }
        }
    }
    for (int i = 1;i < n;i++) {
        l[i] = max(l[i],l[i-1]);
    }
    for (int i = n - 2;i >= 0;i--) {
        r[i] = min(r[i],r[i+1]);
    }
    int best = -INF;
    int ans_now = 0;
    for (int i = 0;i < n;i++) {
        if (vec[i].second <= 0) {
            ans_now += vec[i].first + l[i] * vec[i].second;
        }else {
            ans_now += vec[i].first + r[i] * vec[i].second;
        }
        if (i >= min_sz - 1) {
            best = max(best,ans_now);
        }
    }
    cout << best;

}