#pragma gcc optimize("Ofast")
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <set>
#include <random>
#include <bitset>
#include <string>
#include <iomanip>
#include <cmath>

using namespace std;
#define int long long
using ll = long long;
using ld = long double;

#ifdef LOCAL
#include "debug.h"
#else
#define dbg(...)
#endif
const int INF = 1e18;
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i] >> b[i];
    }
    vector<int> l(n), r(n);
    for (int i = 0; i < n; i++) {
        r[i] = i + 1;
    }
    vector<int> p(n);
    int bound = 0;
    for (int i = 0; i < n; i++) {
        cin >> p[i];
        bound = max(bound, p[i]);
        if (p[i] == -1) continue;
        r[p[i] - 1] = min(r[p[i] - 1], i + 1);
        for (int j = p[i]; j < n; j++) {
            l[j] = max(l[j], i + 1);
        }
    }
    vector<vector<int>> dp(n + 1, vector<int> (n, -INF));
    dp[0][0] = 0;
    for (int i = 1; i <= n; i++) {
        int curmx = -INF, prt = 0;
        for (int curt = l[i - 1]; curt < r[i - 1]; curt++) {
            while (prt <= curt) {
                curmx = max(curmx, dp[i - 1][prt] + a[i - 1] + curt * b[i - 1]);
                prt++;
            }
            dp[i][curt] = max(dp[i][curt], curmx);
            // for (int prt = 0; prt <= curt; prt++) {
            //     dp[i][curt] = max(dp[i][curt], dp[i - 1][prt] + a[i - 1] + curt * b[i - 1]);
            // }
        }
    }
    dbg(l, r);
    dbg(dp[0]);
    dbg(dp[1]);
    int ans = -INF;
    for (int i = bound; i <= n; i++) {
        for (int t = 0; t < n; t++) {
            ans = max(ans, dp[i][t]);
        }
    }
    cout << ans << '\n';
}
