#include <bits/stdc++.h>

using ll = long long int;
using ull = unsigned long long int;

using namespace std;

#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

const ll INF = 1e12;

void solve()
{
    int n;
    cin >> n;
    
    vector<ll> a(n);
    vector<ll> b(n);
    for (int i = 0; i < n; i++)
        cin >> a[i] >> b[i];
    vector<ll> min_val(n + 1);
    vector<ll> max_val(n + 1);
    vector<int> p(n);
    for (int i = 0; i < n; i++)
    {
        int x;
        cin >> x;
        p[i] = x;
        if (x != -1)
        {
            max_val[i] = i + 1;
            max_val[x] = -(i + 1);

            min_val[x] = i + 1;
            min_val[n] = -(i + 1);
        }
    }


    vector<ll> pa(n + 1);
    vector<ll> pb(n + 1);
    partial_sum(all(a), pa.begin() + 1);
    partial_sum(all(b), pb.begin() + 1);

    ll ans = 0;
    ll cur = 0;

    multiset<ll> st1;
    st1.insert(0);
    multiset<ll> st2;
    st2.insert(n);

    int cnt = 0;
    for (int i = 0; i < n; i++)
    {
        cnt = max({cnt, i + 1, p[i]});
        if (min_val[i] < 0)
            st1.extract(-min_val[i]);
        else if (min_val[i] > 0)
            st1.insert(min_val[i]);
        if (max_val[i] < 0)
            st2.extract(-max_val[i]);
        else if (max_val[i] > 0)
            st2.insert(max_val[i]);
        ll mn = *st1.rbegin();
        ll mx = min((*st2.begin()) - 1, (ll)i);
        if (b[i] <= 0)
            cur += a[i] + b[i] * mn;
        else
            cur += a[i] + b[i] * mx;
        ans = max(ans, cur + (pb[cnt] - pb[i + 1]) * mn + pa[cnt] - pa[i + 1]);
    }
    cout << ans << '\n';
}

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

    int t = 1;
#ifdef LOCAL
    freopen("C:/work/in.txt", "r", stdin);
    freopen("C:/work/out.txt", "w", stdout);
    cin >> t;
#endif

    while (t--)
        solve();
    return 0;
}