#pragma GCC optimize("O3,unroll-loops")
#include<vector>
#pragma GCC target("avx,avx2")
#include<bits/stdc++.h>
using namespace std;

using ll = long long;
using ld = long double;

#ifdef DBG
#define $(x) x
#else
#define $(x)
#endif

#define debug(x) $(cout << #x << " = " << x << endl)

#define all(x) x.begin(), x.end()

constexpr int INF = 1e9 + 7;
constexpr ll LINF = 1e18 + 7;

void WA() {
    cout << "THIS IS WRONG ANSWER" << endl;
    exit(0);
}

void RE() {
    exit(1);
}

void TL() {
    unsigned x = 0;
    while (true) x++;
}

void solve() {
    int n;
    cin >> n;
    vector<ll> a(n), b(n);


    ll ans = 0;

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

    vector<ll> p(n + 1, 0);
    for (int i = 0; i < n; ++i) {
        cin >> p[i + 1];
    }


    ll pi = 0, pv = 0;

    vector<ll> px(n + 1);

    for (int i = 0; i < n; ++i) {
        if (p[i + 1] == -1) continue;
        
        ll v = p[i + 1];

        px[pv] = 0;
        ll mn = 0;
        ll sm = 0;
        for (int j = pv; j < v; ++j) {
            px[j + 1] = px[j] + b[j];
            if (px[j + 1] < mn) {
                mn = px[j + 1];         
            }
            sm += b[j];
            ans += a[j] + b[j] * pi;
        }

        sm -= mn;

        ans += sm * (i - pi);

        vector<ll> dp(n);


        pi = i;
        pv = v;
    }
    ll sm = 0;
    ll mn = 0;

    ll ca = 0;
    ll ma = 0;
    for (int j = pv; j < n; ++j) {
        sm += b[j] * (j - pi);
        mn = min(mn, sm);
        ca += a[j] + b[j] * pi;

        debug(ca << ' ' << sm << ' ' << mn << ' ' <<  j << ' ' << pi); 
        ma = max(ma, ca + sm - mn);
    }

    cout << ans + ma << '\n';
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
    $(cin >> t);
    while (t--) {
        debug("=-=-=-=-=-=-=-=");
        solve();
    }
}