#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <set>
#include <map>
#include <random>
#include <deque>
#include <queue>
#include <unordered_set>
#include <unordered_map>

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

using namespace std;

mt19937 rnd(52);

typedef long long ll;
typedef long double ld;

const ll MAXN = 5e5 + 1;
const ll MOD = 998244353;
const ll INF = 1e18;

int logpow(int num, int deg, int mod = MOD){
    int sum = 1;
    while(deg){
        if(deg % 2 == 0){
            num *= num;
            num %= mod;
            deg /= 2;
        }
        else{
            sum *= num;
            sum %= mod;
            deg--;
        }
    }
    return sum;
}

vector<int> mirror(vector<int> arr){
    int n = arr.size() - 1;
    vector<int> newarr(n + 1);
    for(int i = 1; i <= n; i++){
        newarr[i] = arr[n - i + 1];
    }
    return newarr;
}

vector<int> rev(vector<int> arr){
    int n = arr.size() - 1;
    vector<int> newarr(n + 1);
    for(int i = 1; i <= n; i++){
        newarr[i] = n - arr[i] + 1;
    }
    return newarr;
}

vector<int> obr(vector<int> arr){
    int n = arr.size() - 1;
    vector<int> newarr(n + 1);
    for(int i = 1; i <= n; i++){
        newarr[arr[i]] = i;
    }
    return newarr;
}


void solve(){
    int n;
    cin >> n;
    vector<pair<int, int>> arr(n + 1);
    for(int i = 1; i <= n; i++){
        int a, b;
        cin >> a >> b;
        arr[i] = {a, b};
    }
    vector<int> pr(n + 1);
    for(int i = 1; i <= n; i++){
        cin >> pr[i];
    }
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, -INF));
    dp[0][0] = 0;
    int ind = 0;
    for(int i = 1; i <= n; i++){
        if(pr[i] == -1){
            for(int j = i; j <= n; j++){
                int sum_a = 0;
                int sum_b = 0;
                for(int k = j + 1; k >= i; k--){
                    if(k != j + 1){
                        sum_a += arr[k].first;
                        sum_b += arr[k].second;
                    }
                    dp[j][i] = max(dp[j][i], dp[k - 1][i - 1] + sum_b * (i - 1) + sum_a);
                }
            }
        }
        else{
            ind = i;
            int j = pr[i];
            int sum_a = 0;
            int sum_b = 0;
            for(int k = j + 1; k >= i; k--){
                if(k != j + 1){
                    sum_a += arr[k].first;
                    sum_b += arr[k].second;
                }
                dp[j][i] = max(dp[j][i], dp[k - 1][i - 1] + sum_b * (i - 1) + sum_a);
            }
        }
    }
    int ans = -INF;
    for(int i = ind; i <= n; i++){
        for(int j = 0; j <= n; j++){
            ans = max(ans, dp[j][i]);
        }
    }
    cout << ans << endl;
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
}