#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>
#include<cassert>

#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];
ll dp[N];
vector<pair<ll, ll>> s;
ll rval;


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);
	s.push_back({ 0, 0 });
	rval = 0;
	int mxl = 0;
	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]);
		dp[i + 1] = dp[i];*/
		rval += 1ll * b[i] * i + a[i];
		ll k = -b[i], j = i;
		while (k > 0 && !s.empty()) {
			ll k1 = s.back().second;
			rval += k * (j - s.back().first);
			j = s.back().first;
			if (k1 < k) {
				k -= k1;
				s.pop_back();
			}
			else if (k1 > k) {
				s.back().second -= k;
				break;
			}
			else {
				s.pop_back();
				break;
			}
		}
		if (k < 0) {
			s.push_back({ i + 1, -k });
		}
		if (s.empty()) {
			s.push_back({ mxl, 0 });
		}
		if (cmx[i] != -1) {
			while (!s.empty()) {
				int j = s.back().first;
				ll k = s.back().second;
				if (j <= cmn[i]) {
					rval -= k * (i + 1 - cmn[i]);
					break;
				}
				else {
					rval -= k * (i + 1 - j);
					s.pop_back();
				}
			}
			s.clear();
			mxl = cmx[i] + 1;
			s.push_back({ mxl, rval });
		}
		if (i >= mxind) ans = max(ans, rval);
	}
	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;
}