#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")

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

struct SegmentTree {
	vector<int> tree;
	int size;
	void init(int n) {
		size = 1;
		while (size < n) size *= 2;
		tree.assign(2 * size - 1, -1);
	}
	void set(int i, int x) {
		i += size - 1;
		tree[i] = x;
		while (i > 0) {
			i = (i - 1) >> 1;
			tree[i] = std::max(tree[2 * i + 1], tree[2 * i + 2]);
		}
	}
	int max(int lx, int rx, int l, int r, int v) {
		if (rx <= l || r <= lx) return -1;
		if (lx <= l && r <= rx) return tree[v];
		int m = (l + r) >> 1;
		return std::max(max(lx, rx, l, m, 2 * v + 1), max(lx, rx, m, r, 2 * v + 2));
	}
	int max(int l, int r) {
		if (l > r) return -1;
		return max(l, r + 1, 0, size, 0);
	}
};

signed main() {
	ios_base::sync_with_stdio(0); cin.tie(0);

	int n;
	cin >> n;
	vector<int> a(n), b(n);
	for (int i = 0; i < n; ++i) {
		cin >> a[i] >> b[i];
	}

	vector<ll> pref_a(n), pref_b(n);
	pref_a[0] = a[0];
	pref_b[0] = b[0];
	for (int i = 1; i < n; ++i) {
		pref_a[i] = pref_a[i - 1] + a[i];
		pref_b[i] = pref_b[i - 1] + b[i];
	}
	
	function<ll(int, int)> sum_a = [&](int l, int r) -> ll {
		return pref_a[r] - (l == 0 ? 0 : pref_a[l - 1]);
	};
	function<ll(int, int)> sum_b = [&](int l, int r) -> ll {
		return pref_b[r] - (l == 0 ? 0 : pref_b[l - 1]);
	};
	
	vector<int> p(n);
	for (int i = 0; i < n; ++i) {
		cin >> p[i];
	}

	vector<int> first(n);

	for (int i = n - 1; i >= 0; --i) {
		if (p[i] == -1) {
			first[i] = (i == n - 1 ? -1 : first[i + 1]);
		} else {
			first[i] = i;
		}
	}

	vector<int> last(n);
	SegmentTree st;
	st.init(n);

	for (int i = n - 1; i >= 0; --i) {
		if (first[i] == -1) {
			last[i] = -1;
		} else if (p[i] == -1) {
			last[i] = -1;
		} else {
			last[i] = std::max(p[i], st.max(i, p[i]));
		}
		st.set(i, last[i]);
	}

	vector<int> min_can(n), max_can(n, -1);

	for (int i = 0; i < n; ++i) {
		min_can[i] = i;
	}

	for (int i = 0; i < n; ++i) {
		if (p[i] != -1) {
			int jt = p[i] - 1;
			for (int k = i; k <= jt; ++k) {
				min_can[k] = std::min(min_can[k], i);
				max_can[k] = std::max(max_can[k], i);
			}
		}
	}

	for (int i = 0; i < n; ++i) {
		if (max_can[i] == -1) {
			max_can[i] = i;
		}
	}

	vector<ll> dp(n + 1);
	dp[0] = LLONG_MIN;

	for (int i = n - 1; i >= 0; --i) {
		for (int j = i; j < (first[i] == -1 ? n : first[i]); ++j) {
			dp[i] = std::max(dp[i], dp[j + 1] + sum_a(i, j) + sum_b(i, j) * 1ll * max_can[i]);
			dp[i] = std::max(dp[i], dp[j + 1] + sum_a(i, j) + sum_b(i, j) * 1ll * min_can[i]);
		}
		if (first[i] != -1) {
			int jt = p[first[i]] - 1;
			dp[i] = std::max(dp[i], dp[jt + 1] + sum_a(i, jt) + sum_b(i, jt) * 1ll * min_can[i]);
			dp[i] = std::max(dp[i], dp[jt + 1] + sum_a(i, jt) + sum_b(i, jt) * 1ll * max_can[i]);
		}
	}

	cout << dp[0];
}
