// 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()

#pragma GCC optimize("Ofast")


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);
    int cnt = 0;
    for (auto &[a, b] : v) {
        cin >> a >> b;
        if (b > 0) cnt++;
    }
    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;
        // mxP = max(mxP, p);
        // 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;
    // }
    ll bst = -INF;
    vector<pll>v_;
    vector<int>cnt2;
    for (int i = 0; i < n; ++i) {
        if (v_.empty() || v[i].second > 0) {
            v_.push_back(v[i]);
            cnt2.push_back(1);
        } else {
            v_.back().first += v[i].first;
            v_.back().second += v[i].second;
            cnt2.back()++;
        }
    }
    v = v_;
    vector<ll>dp(n, -INF);
    for (int msk = 0; msk < (1 << cnt); ++msk) {
        int pt = 0;
        int c = 0;
        for (int i = 0; i < len(v); ++i) {
            c += cnt2[i];
            auto [a, b] = v[i];
            int t = pt;
            if (b > 0 && (msk & 1)) {
                t = c - 1;
            }
            dp[i] = a + t * b + (i == 0 ? 0 : dp[i - 1]);
            if (b > 0) {
                msk /= 2;
            }
            pt = t;
            bst = max(bst, dp[i]);
        }
    }
    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';
    }
}