#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<iomanip>
#include<queue>
#include<string>
#include<unordered_map>
#include<unordered_set>
#include<bitset>
#include<cmath>
#include<algorithm>
#include<random>
#include<ctime>

#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx,avx2,bmi,popcnt")

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using uint = unsigned int;

mt19937 mt(time(0));
const int N = 5e3 + 2, inf = 1e9 + 100;
const ll llinf = 1e18 + 1000;
int n, a[N], b[N], cmn[N], cmx[N], mnt;
ll dp[N];

void solve() {
	cin >> n;
	for (int i = 0; i < n; ++i) cin >> a[i] >> b[i];
	fill(cmx, cmx + n, -1);
	fill(cmn, cmn + n, inf);
	int mxind = -1;
	for (int i = 0; i < n; ++i) {
		int x;
		cin >> x;
		if (x != -1) {
			--x;
			cmn[x] = min(cmn[x], i);
			cmx[x] = max(cmx[x], i);
		}
		mxind = max(mxind, x);
	}
	ll ans = (mxind <= 0 ? 0 : -llinf);
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j <= i; ++j) dp[j] += 1ll * b[i] * j + a[i];
		for (int j = 1; j <= i; ++j) dp[j] = max(dp[j], dp[j - 1]);
		if (cmx[i] != -1) {
			for (int j = 0; j <= i + 1; ++j) {
				if (j != cmn[i]) dp[j] = -llinf;
			}
			for (int j = cmx[i] + 1; j <= i + 1; ++j) {
				dp[j] = dp[cmx[i]];
			}
			for (int j = cmn[i]; j <= cmx[i]; ++j) dp[j] = -llinf;
		}
		dp[i + 1] = dp[i];
		if(i >= mxind) ans = max(ans, dp[i]);
		if (cmx[i] != -1) {
			for (int j = cmn[i]; j <= cmx[i]; ++j) dp[j] = -llinf;
		}
	}
	cout << ans;
}

signed main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	int tt = 1;
	//cin >> tt;
	while (tt--) {
		solve();
		cout << '\n';
		cout.flush();
	}
	return 0;
}