#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <cmath>
#include <iomanip>

using namespace std;
using ll = long long;
using ld = long double;

#define int ll

const int MOD = 998'244'353;
const int SIGNES = 6;
const int INF = 1e9;

void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    vector<int> b(n);
    vector<int> p(n);
    bool les0 = true;
    bool bigger0 = true;
    for (int i = 0; i < n; i++) {
        cin >> a[i] >> b[i];
        if (b[i] > 0) {
            les0 = false;
        }
        if (b[i] < 0) {
            bigger0 = false;
        }
    }
    bool pi = true;
    for (auto &i : p) {
        cin >> i;
        if (i != -1) {
            pi = false;
        }
    }
    if (les0) {
        int ans = 0;
        int t = 0;
        if (pi) {
            vector<int> pref(n);
            for (int i = 0; i < n; i++) {
                pref[i] = ((i > 0? pref[i - 1] : 0) + a[i]);
                ans = max(ans, pref[i]);
            }
        } else {
            vector<int> t(n);
            int last = 0;
            for (int i = 0; i < n; i++) {
                if (p[i] != -1) {
                    for (int j = last; j < p[i]; j++) {
                        t[j] = i;
                    }
                }
            }
            for (int i = last; i < n; i++) {
                t[i] = t[i - 1];
            }
            int ans = 0;
            vector<int> pref(n);
            for (int i = 0; i < n; i++) {
                pref[i] = ((i > 0? pref[i - 1] : 0) + a[i] + b[i] * t[i]);
                ans = max(ans, pref[i]);
            }
        }
        cout << ans << '\n';
    } else if (bigger0) {
        int ans = 0;
        if (pi) {
            vector<int> pref(n);
            for (int i = 0; i < n; i++) {
                pref[i] = ((i > 0? pref[i - 1] : 0) + a[i] + i * b[i]);
                ans = max(ans, pref[i]);
            }
        }
        cout << ans << '\n';
    }
}

signed main() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(SIGNES);

    int q = 1;

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

    while (q--) {
        solve();
    }

}