#include <bits/stdc++.h>

using namespace std;
#define int long long

const int N = 1100000;
const int INF = (int)(4e18);

int n, a[N], b[N], p[N], l[N], r[N], v[N];
vector<int> pos;

int32_t main() {
    ios::sync_with_stdio(0); cin.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i] >> b[i];
        l[i] = 0;
        r[i] = i - 1;
    }
    for (int i = 1; i <= n; i++)
        cin >> p[i];
    pos.push_back(n);
    for (int i = 1; i <= n; i++) {
        if (p[i] == -1) continue;
        r[p[i]] = min(r[p[i]], i - 1);
        l[p[i] + 1] = max(l[p[i] + 1], i);
        pos.push_back(p[i]);
    }
    sort(begin(pos), end(pos));
    pos.erase(unique(begin(pos), end(pos)), end(pos));
    for (int i = 1; i + 1 <= n; i++)
        l[i + 1] = max(l[i], l[i + 1]);
    for (int i = n; i - 1 >= 1; i--)
        r[i - 1] = min(r[i], r[i - 1]);
    for (int i = 1; i <= n; i++)
        assert(l[i] <= r[i]);
    int sl = 1, sum = 0;
    int ans = -INF;
    if ((int) pos.size() == 1) ans = 0;
    for (int x : pos) {
        int sr = x;
        assert(l[sl] == l[sr]);
        assert(sr == n || r[sr] < l[sr + 1]);
        for (int i = sr; i >= sl; i--)
            v[i] = v[i + 1] + b[i];
        vector<array<int, 4>> st; // [0] - slope, [1] - position, [2] - value
        st.push_back({INF, 0, 0});
        st.push_back({-INF, 0, 0});
        int opt = -INF, pref = 0, val = 0;
        for (int i = sl; i <= sr; i++) {
            int lim = r[i] - l[i];
            int k = v[i], last = -1;
            while (!st.empty() && st.back()[0] < k) {
                last = st.back()[1];
                st.pop_back();
            }
            assert(last != -1);
            assert(!st.empty());
            int len = last - st.back()[1];
            int nval = st.back()[2] + len * st.back()[0];
            st.push_back({k, last, nval});
            st.push_back({-INF, lim, nval + k * (lim - last)});
            int tl = 0, tr = (int) st.size() - 1;
            while (tr - tl > 1) {
                int tm = (tl + tr) / 2;
                if (st[tm][0] - v[i + 1] >= 0) tl = tm;
                else tr = tm;
            }
            val += a[i] + l[i] * b[i];
            int cur = st[tr][2] - v[i + 1] * st[tr][1] + val;
            opt = max(opt, cur);
            pref = cur;
        }
        ans = max(ans, sum + opt);
        sum += pref;
        sl = sr + 1;
    }
    cout << ans;
}