//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define int long long
#define ld long double
#define pb push_back
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define coutp cout << "       "
#define cont continue
#define F first
#define S second

using namespace std;
using namespace __gnu_pbds;

template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

template<typename T>
istream& operator>> (istream& in, pair<T, T>& a) {
    in >> a.F >> a.S;
    return in;
}

template<typename T>
ostream& operator<< (ostream& os, pair<T, T>& a) {
    os << a.F << " " << a.S;
    return os;
}

template<typename T>
istream& operator>> (istream& in, vector<T>& a) {
    for (auto& x : a) {
        in >> x;
    }
    return in;
}

template<typename T>
ostream& operator<< (ostream& os, vector<T>& a) {
    for (auto& x : a) {
        os << x << " ";
    }
    return os;
}

constexpr int inf = 2e18, mod = 998244353;
constexpr ld eps = 1e-9;

int add(int a, int b) {
    return (a + b) % mod;
}

int mul(int a, int b) {
    return (a * b) % mod;
}

int fast_pow(int a, int k) {
    if (k == 0) {
        return 1;
    }
    int q = fast_pow(a, k / 2);
    q = mul(q, q);
    if (k % 2 == 1) {
        q = mul(q, a);
    }
    return q;
}

int mi(int a, int b) {
    return (a + mod - b) % mod;
}

int32_t main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int multitest = 1; //cin >> multitest;
    while (multitest--) {
        int n; cin >> n;
        vector<int> a(n), b(n);
        for (int i = 0; i < n; i++) {
            cin >> a[i] >> b[i];
        }
        vector<int> p(n); cin >> p;
        vector<int> dop(n + 1, inf);
        for (int i = 0; i < n; i++) {
            if (p[i] == -1) {
                cont;
            }
            dop[p[i] - 1] = min(dop[p[i]], i);
        }
        vector<int> mx(n);
        int ans = -inf;
        int qqq = *max_element(all(p));
        if (qqq == -1) {
            ans = 0;
        }
        int q = inf;
        for (int i = n - 1; i >= 0; i--) {
            q = min({q, dop[i], i + 1});
            mx[i] = q;
        }
        cout << mx << endl;
        int s = 0;
        for (int i = 0; i < n; i++) {
            s += a[i] + b[i] * mx[i];
            if (i + 1 >= qqq) {
                ans = max(ans, s);
            }
        }
        cout << ans;
    }
    return 0;
}

/*
4
3 -6
4 -10
-7 -3
-3 6
3 3 -1 -1

4
-6 -1
-5 14
0 10
-30 2
2 3 -1 -1
*/
