扎西德勒

#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
int n;
vector<vector<int>> children;
vector<int> val;
unordered_map<int, int> mdp;
int lchild(int root){
    if(children[root].size() == 0){
        return -1;
    }
    else{
        return children[root][0];
    }
}
int rchild(int root){
    if(children[root].size() <= 1){
        return -1;
    }
    else{
        return children[root][1];
    }
}
int rob(int root){
    if(mdp.find(root) != mdp.end()){
        return mdp[root];
    }
    if(root == -1){
        return 0;
    }
    if(children[root].size() == 0){
        return val[root];
    }
    int l = lchild(root);
    int r = rchild(root);
    int ans1 = rob(l) + rob(r);
    int ans2 = val[root] + (l == -1 ? 0 : rob(lchild(l)) + rob(rchild(l))) + (r == -1 ? 0 : rob(lchild(r)) + rob(rchild(r)));
    mdp[root] = ans1 > ans2 ? ans1 : ans2;
    return mdp[root];
}
int main(){
    cin >> n;
    children.resize(n + 1);
    val.resize(n + 1);
    for(int i = 1; i <= n; ++i){
        cin >> val[i];
    }
    for(int i = 1; i <= n; ++i){
        int a;
        cin >> a;
        children[a].push_back(i);
    }
    cout << rob(children[0][1]) << endl;
    return 0;
}