#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;

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

        ll sm = 0;
        ll ca = 0;

        vector<ll> st;

        for (ll j = v - 1; j >= pv; --j) {
            ca += a[j] + b[j] * pi;
            sm += b[j];
            if (sm >= 0) {
                ca += sm * (min(j, i) - pi);
                sm = 0;
            }
        }
 
        
        ans += ca;

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

    ll ca = 0;
    ll ma = 0;
    ll pr = pi;

    vector<tuple<ll, ll, ll>> st; //sm, h, val
    for (int j = pv; j < n; ++j) {
        ca += a[j] + b[j] * pi;
        if (b[j] > 0) {
            ll val = 0;
            if (st.size()) {
                auto [_, __, v] = st.back();
                val += v + _ * __;

            }
            st.push_back({b[j], j - pi, val});
        } else {
            if (st.size()) {
                auto& [val, _, __] = st.back();
                val -= b[j];
                while (st.size()) {
                    auto [v, _, __] = st.back();
                    if (v > 0) break;
                    st.pop_back();

                    if (st.size()) {
                        auto& [nv, _, __] = st.back();
                        nv += v;
                    } 
                } 
            }
        }

        ll ad = 0;
        if (st.size()) {
            auto [_, __, ___] = st.back();
            ad = _ * __ + ___;
        }
        ma = max(ma, ca + ad);
    }

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

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

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