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

#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];
bool mrk[N];

int 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 = 0; i < n; ++i) {
        cin >> a[i] >> b[i];
    }
    for (int i = 0; i < n; ++i) {
        cin >> p[i];
        --p[i];
        if (p[i] >= 0 && pp[p[i]] == -1) pp[p[i]] = i;
    }
    ans = LLONG_MIN;
    ll suma = 0;
    for (int k = 0; k < n; ++k) {
        ll res = 0, si = 0;
        suma += a[k];
        for (int i = 0; i <= k; ++i) {
            mrk[i] = 0;
        }
        pmx[k] = max(b[k], 0);
        val[k] = b[k];
        if (b[k] > 0) mrk[k] = 1;
        for (int i = k - 1; i >= 0; --i) {
            val[i] = val[i + 1] + b[i];
            if (val[i] > pmx[i + 1])
                mrk[i] = 1;
            pmx[i] = max(pmx[i + 1], val[i]);
        }
        int l = 1;
        for (int i = 0; i <= k; ++i) {
            int j = i;
            while (j <= k && pp[j] == -1) {
                ++j;
            }
            if (j <= k) {
                ll best = 0;
                ll mm = (j + 1 <= k ? val[j + 1] : 0);
                for (int h = i; h <= j; ++h)
                    umx(best, val[i] - mm);
                res += mm * (pp[j] - l + 1);
                res += best * (pp[j] - l + 1);
                l = pp[j] + 1;
                i = j;
            } else {
                for (int h = i; h <= k; ++h) {
                    if (mrk[h]) {
                        res += pmx[h] * (h - l + 1);
                        l = h + 1;
                    }
                }
                break;
            }
        }

        res += suma;
//        cout << res << " " << k << "\n";
        umx(ans, res);
    }
    cout << ans;
}
