#include <bits/stdc++.h>

#ifndef LOCAL
#pragma GCC optimize("O3")
#endif

using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
using pii = pair<int, int>;

const int mod = 1e9 + 7;

struct mint
{
    int x;

    mint(int x = 0) : x(x) {}

    friend mint operator+(mint a, mint b)
    {
        int res = a.x + b.x;
        return res - (res >= mod ? mod : 0);
    }

    friend mint operator-(mint a, mint b)
    {
        int res = a.x - b.x;
        return res + (res < 0 ? mod : 0);
    }

    friend mint operator*(mint a, mint b)
    {
        return ll(a.x) * b.x % mod;
    }
};

mint mpow(mint a, ll b)
{
    mint res = 1;
    while (b)
    {
        if (b & 1)
        {
            res = res * a;
        }
        a = a * a;
        b >>= 1;
    }
    return res;
}

ll calc(vector<ll> &a, vector<ll> &b, ll st, ll mx, bool f)
{
    int n = a.size();
    if (n == 0)
    {
        return 0;
    }
    vector<ll> pr(n + 1);
    for (int i = 0; i < n; ++i)
    {
        pr[i + 1] = pr[i] + b[i];
    }
    ll cur = 0;
    vector<int> p(n + 1);
    vector<ll> ans(n + 1);
    ll cans = 0;
    for (int i = 1; i <= n; ++i)
    {
        cur += a[i - 1];
        p[i] = i - 1;
        while (p[i] > 0 && pr[p[i]] >= pr[i])
        {
            p[i] = p[p[i]];
        }
        ans[i] = ans[p[i]] + (pr[i] - pr[p[i]]) * min(p[i] + st, mx);
        cans = max(cans, cur + ans[i]);
    }
    if (f)
    {
        return cur + ans.back();
    }
    return cans;
}

void solve()
{
    int n;
    cin >> n;
    vector<ll> a(n), b(n);
    for (int i = 0; i < n; ++i)
    {
        cin >> a[i] >> b[i];
    }
    vector<int> p(n);
    vector<ll> buf1, buf2;
    ll ans = 0;
    int st = 0;
    int lst = 0;
    int sp = 0;
    for (int i = 0; i < n; ++i)
    {
        cin >> p[i];
        if (p[i] != -1)
        {
            st = max(st, lst);
            while (lst < p[i])
            {
                buf1.push_back(a[lst]);
                buf2.push_back(b[lst]);
                ++lst;
            }
            ans += calc(buf1, buf2, st, i, true);
            buf1.clear();
            buf2.clear();
            st = i + 1;
            sp = i + 1;
        }
    }
    if (sp <= lst) {
        st = max(st, lst);
        while (lst < n)
        {
            buf1.push_back(a[lst]);
            buf2.push_back(b[lst]);
            ++lst;
        }
        ans += calc(buf1, buf2, st, n - 1, false);
    }
    cout << ans << '\n';
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
#endif
    solve();
}