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

#define int ll
#define ll long long
#define debug(x) cerr << (#x) <<  " = " << x << "\n";
#define pb push_back
#define pii pair < int, int >
#define pll pair < ll, ll >
#define sz(x) (ll)(x.size())

const int N = 2e5 + 5;
const int mod = 998244353;

using namespace std;
using namespace __gnu_pbds;

template<typename T>
using oset = tree <T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

template<typename T>
bool umx (T &a, T b) {
    return (a < b ? (a = b, 1) : 0);
}

template<typename T>
bool umn (T &a, T b) {
    return (a > b ? (a = b, 1) : 0);
}

int add (int x, int y) {
    x += y;
    if (x >= mod)
        x -= mod;
    return x >= 0 ? x : x + mod;
}

int mul (int x, int y) {
    return 1ll * x * y % mod;
}

int power (int x, int y) {
    int res = 1;
    while (y) {
        if (y % 2)
            res = mul(res, x);
        x = mul(x, x);
        y >>= 1;
    }
    return res;
}

mt19937 rnd(42);

int n, q;
int pp[N], a[N], b[N], p[N], to[N], la[N], res[N], res_, cur[N];

ll pmx[N], val[N], maxp[N], cl[N], pans[N];
bool mrk[N];

signed main () {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin >> n;
    ll ans = 0;
    for (int i = 0; i <= n; ++i)
        pp[i] = -1;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i] >> b[i];
    }
    bool flag = 0;
    for (int i = 1; i <= n; ++i) {
        cin >> p[i];
        if (p[i] >= 0) flag = 1;
        if (p[i] >= 0 && pp[p[i]] == -1) pp[p[i]] = i;
        if (p[i] >= 0) maxp[p[i]] = i;
    }
    for (int i = n; i >= 0; --i) {
        val[i] = b[i] + val[i + 1];
    }
    ans = 0;
    ll suma = 0;
    vector < int > st;
    for (int k = 1; k <= n; ++k) {
        ll res = 0, si = 0;
        suma += a[k];
        for (int i = 0; i <= k; ++i) {
            mrk[i] = 0;
        }

        ll cur = val[k], mm = val[k + 1];
        while (sz(st) && val[st.back()] < val[k]) {
            st.pop_back();
        }
        if (sz(st)) {
            int j = st.back();
            pans[k] = pans[j];
            if (val[k] > mm)
                pans[k] += (k - cl[j]) * val[k], cl[k] = k;
            else
                cl[k] = cl[j];
        } else {
            if (val[k] > mm)
                pans[k] = val[k] * (k - 1), cl[k] = k;
            else cl[k] = 1;
        }
        st.push_back(k);

        res = pans[k] - (cl[k] - 1) * mm;
        res += suma;
//        cout << res << " " << k << "\n";
        umx(ans, res);
        continue;

    }
    cout << ans;
}
