// dimaloh

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;
using ll = long long;
using lll = __int128;
using pii = pair<int, int>;
using ld = long double;
using pll = pair<ll, ll>;

#define len(v) (int)v.size()
#define all(v) v.begin(), v.end()


template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

const ll INF = 1e18;
const int inf = 1e9, mod = 1e9 + 7, sz = 5e5 + 10, logn = 20;
const ld pi = acosl(-1), eps = 1e-8;

mt19937 rnd(87438);

void solve() {
    int n; cin >> n;
    vector<pll>v(n);
    for (auto &[a, b] : v) {
        cin >> a >> b;
    }
    vector<int>pref(n, n), suff(n, 0);
    // cout << '!' << endl;
    for (int i = 0; i < n; ++i) {
        int p; cin >> p;
        p--;
        if (p == -2) continue;
        pref[p] = min(pref[p], i);
        if (p != n - 1) suff[p + 1] = max(suff[p + 1], i + 1);
    }
    vector<int>l(n, 0), r(n, n);
    for (int i = 0; i < n; ++i) {
        l[i] = max(i == 0 ? 0 : l[i - 1], suff[i]);
    }
    for (int i = n - 1; i >= 0; --i) {
        r[i] = min(i == n - 1 ? n : r[i + 1], pref[i]);
    }
    for (int i = 0; i < n; ++i) {
        r[i] = min(r[i], i);
    }
    // for (int i = 0; i < n; ++i) {
    //     cout << l[i] << ' ' << r[i] << endl;
    // }
    vector<vector<ll>>dp(n, vector<ll>(n, -INF));
    ll bst = -INF;
    for (int i = 0; i < n; ++i) {
        auto [a, b] = v[i];
        for (ll t = l[i]; t <= r[i]; ++t) {
            ll cur = a + t * b;
            ll add = 0;
            if (i != 0) {
                add = -INF;
                for (int tp = 0; tp <= t; ++tp) {
                    add = max(add, dp[i - 1][tp]);
                }
            }
            dp[i][t] = cur + add;
            bst = max(bst, dp[i][t]);
        }
    }
    cout << bst;
}

signed main() {
    cin.tie(0)->sync_with_stdio(0);
    cout.precision(20);

    int t = 1;

#ifdef DEBUG
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    cin >> t;
#endif


    while (t--) {
        solve();
        cout << '\n';
    }
}