// template.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#pragma GCC optimize("O3")
#include <bits/stdc++.h>
// #define int long long

using namespace std;
using ll = long long;
using ld = long double;

const int MOD = 998244353;

int modpow(int a, int b)
{
    if (b == 0)
        return 1;
    if (b & 1)
        return 1ll * a * modpow(a, b - 1) % MOD;
    return modpow(1ll * a * a % MOD, b >> 1);
}

const int MAXN = 1e6 + 10;

int a[MAXN], b[MAXN], mn[MAXN], mx[MAXN];
ll dp[2][MAXN];

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    memset(mn, 0, sizeof(mn));
    memset(dp, 0, sizeof(dp));
    int n;
    cin >> n;
    for (size_t i = 0; i < n; i++)
    {
        cin >> a[i] >> b[i];
    }
    for (size_t i = 0; i <= n; i++)
    {
        mx[i] = i + 1;
    }
    int k = 0;
    for (size_t i = 0; i < n; i++)
    {
        int pi;
        cin >> pi;
        if (pi == -1)
            continue;
        pi--;
        mx[pi] = min(mx[pi], (int)i + 1);
        mn[pi + 1] = max(mn[pi + 1], (int)i + 1);
        k = max(k, pi - 1);
    }
    /*for (size_t i = 0; i < n; i++)
    {
        mn[i + 1] = max(mn[i], mn[i + 1]);
    }
    for (int i = n - 1; i >= 0; i--)
    {
        mx[i] = min(mx[i], mx[i + 1]);
    }*/
    for (int i = n - 1; i >= 0; i--)
    {
        auto cdp = dp[i & 1];
        auto pdp = dp[(i & 1) ^ 1];
        ll cur = (i < k ? (ll)-1e18 : 0ll);
        // ll cur = -1e18;
        for (int j = mx[i]; j <= i; j++)
            cdp[j] = -1e18;
        for (int j = mx[i] - 1; j >= mn[i]; j--)
        {
            cur = max(cur, pdp[j] + a[i] + 1ll * j * b[i]);
            cdp[j] = cur;
        }
        for (int j = 0; j < mn[i]; j++)
            cdp[j] = cdp[mn[i]];
#ifdef _DEBUG
        cout << "dp = ";
        for (size_t j = 0; j <= i; j++)
        {
            cout << cdp[j] << ' ';
        }
        cout << '\n';
#endif
    }
    cout << dp[0][0] << '\n';
    return 0;
}

// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu

// Tips for Getting Started: 
//   1. Use the Solution Explorer window to add/manage files
//   2. Use the Team Explorer window to connect to source control
//   3. Use the Output window to see build output and other messages
//   4. Use the Error List window to view errors
//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file
