// Created by rost on 05.03.2026.

#include <bits/stdc++.h>

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

const ll INF = 1e18;

struct Student {
  int a, b;
};

void solve() {
  int n;
  cin >> n;
  vector<Student> s(n);
  for (auto &[a, b] : s) cin >> a >> b;
  vector<int> p(n);
  for (auto &e : p) cin >> e;

  vector<vector<ll>> dp(n + 1, vector<ll>(n + 1, -INF));
  dp[0][0] = 0;
  for (int i = 0; i < n; ++i) dp[0][i + 1] = dp[0][i] + s[i].a;

  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= n; ++j) {
      if (p[i - 1] != -1 && j > p[i - 1]) continue;

      if (i == 1 || (p[i - 2] == j || p[i - 2] == -1))
        dp[i][j] = dp[i - 1][j];

      if (i < j)
        dp[i][j] = max(dp[i][j], dp[i][j - 1] + s[j - 1].a + i * s[j - 1].b);
    }
  }

  ll res = -INF;
  for (int i = 0; i <= n; ++i)
    res = max(res, dp[n][i]);
  cout << res << '\n';
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int t = 1;
  // cin >> t;
  while (t--) solve();
}