#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 5e3 + 3, mod = 998244353, inf = 1e18 + 7;
int dp[N][N];
int a[N], b[N], p[N];
signed  main(){
     ios::sync_with_stdio(false);
     cin.tie(nullptr);
     int n;
     cin >> n;
     for (int i = 0; i< n; i++){
        cin >> a[i] >> b[i];
     }
     for (int i = 0 ;i < n; i++){
        cin >> p[i];
        if (p[i] != -1){
            p[i]--;
        }
     }
     int sm = 0;
     for (int i = 0; i< n; i++){
        for (int j = 0; j < n; j++){
            dp[j][i] = -inf;
        }
     }
     for (int  i= 0; i < n; i++){
        sm +=a[i];
        if (p[0] == -1){
            dp[0][i] = sm;
        } else {
            if (i == p[0]){
                dp[0][i] = sm;
            }
        }
        //cout << dp[0][i] << " ";
     }
     //cout << "\n";
     //cout << dp[0][3] << "\n";
     for (int i = 1; i < n; i++){
        if (p[i] != -1){
            for (int t = p[i]; t <= p[i]; t++){
                int sm = 0;
                for (int j = t; j >= 0; j--){
                    dp[i][t] = max(dp[i][t], dp[i - 1][j] + sm);
                    sm += a[j] + b[j] * i;
                }
            }
        } else {
            for (int t = i; t < n; t++){
                int sm = 0;
                for (int j = t; j >= 0; j--){
                    dp[i][t] = max(dp[i][t], dp[i - 1][j] + sm);
                    sm += a[j] + b[j] * i;
                }
            }
        }
        /*for (int j = 0; j < n; j++){
            cout << dp[i][j] << " ";
        }
        cout << "\n";*/
     }
     int ans = -inf;
     for (int i = n - 1; i >= 0; i--){
        for (int j = 0; j < n; j++){
            ans = max(ans, dp[i][j]);
        }
        if (p[i] != -1){
            break;
        }
     }

     cout << ans;
 }

