#include <iostream>
#include <algorithm>
#include <vector>
#include <array>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <cassert>
#include <ctime>
#include <random>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

// #pragma GCC optimize("Ofast")
// #pragma ivdep

using namespace std;
using ll = long long;
using ld = long double;
using lll = __int128;
using pii = pair<int, int>;
// using namespace __gnu_pbds;
// template<class T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

const ll inf = 1e15;

void solve() {
    int n; cin >> n;
    ll a[n], b[n];
    for (int i = 0; i < n; ++i)
        cin >> a[i] >> b[i];

    ll smin[n], pmax[n];
    for (int i = 0; i < n; ++i) {
        smin[i] = i;
        pmax[i] = 0;
    }
    int mk = 0;
    for (ll i = 0; i < n; ++i) {
        int p; cin >> p;
        if (p == -1)
            continue;
        mk = max(mk, p);
        --p;
        smin[p] = min(smin[p], i);
        if (p < n - 1)
            pmax[p + 1] = max(pmax[p + 1], i + 1);
    }
    for (int i = 1; i < n; ++i)
        pmax[i] = max(pmax[i - 1], pmax[i]);
    for (int i = n - 2; i >= 0; --i)
        smin[i] = min(smin[i], smin[i + 1]);

    // for (int i = 0; i < n; ++i)
    //     cout << smin[i] << '\t';
    // cout << '\n';
    // for (int i = 0; i < n; ++i)
    //     cout << pmax[i] << '\t';
    // cout << '\n';

    ll ans;
    if (mk == 0)
        ans = max(0ll, a[0]);
    else if (mk == 1)
        ans = a[0];
    else
        ans = -inf;
    ll dp[n];
    dp[0] = a[0];
    for (int i = 1; i < n; ++i) {
        dp[i] = dp[i - 1] + a[i] + b[i] * pmax[i];
        if (i + 1 >= mk)
            ans = max(ans, dp[i]);
    }
    cout << ans << '\n';
}

int main() {
    cin.tie(0)->sync_with_stdio(0);

    int _ = 1;
    #ifdef DEBUG
        freopen("in.txt", "r", stdin);
        freopen("out.txt", "w", stdout);
        cin >> _;
    #endif

    while (_--) {
        solve();
        cout << '\n';
    }

    return 0;
}
