Source Code
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

vector<int> a, cost, b;

int arr[1000010];
ll mx[1000010];
int idx[1000010];
int pre[1000010];

int main() {


    int n, m;
    scanf("%d%d", &n, &m);

    for(int i = 0; i < n+5; i++){
        mx[i] = -1e18;
        pre[i] = idx[i] = -1;
        arr[i] = -1;
    }

    a.resize(n);
    cost = a;
    b.resize(m);

    for(int &i : a) scanf("%d", &i);
    for(int &i : cost) scanf("%d", &i);
    for(int i = 0; i < m; i++){
        scanf("%d", &b[i]);
        arr[b[i]] = i;
    }

    for(int i = 0; i < n; i++){
        if(arr[a[i]] == -1) continue;
        if(arr[a[i]] == 0){
            if(cost[i] > mx[a[i]]){
                mx[a[i]] = cost[i];
                idx[a[i]] = i;
                pre[i] = -1;
            }
        } else {
            if(idx[b[arr[a[i]]-1]] == -1) continue;
            else {
                if(cost[i] + mx[b[arr[a[i]]-1]] > mx[a[i]]){
                    mx[a[i]] = cost[i] + mx[b[arr[a[i]]-1]];
                    idx[a[i]] = i;
                    pre[i] = idx[b[arr[a[i]]-1]];
                }
            }
        }
    }

    for(int i = 0; i < n+5; i++) arr[i] = 1;
    int cur = idx[b.back()];
    while(cur != -1){
        arr[cur] = 0;
        cur = pre[cur];
    }

    ll ans = 0;
    for(int i = 0; i < n; i++){
        if(arr[i] && cost[i] < 0) ans = ans + cost[i];
    }

    cout << ans << endl;

    return 0;
}

Copy
Always with Me, Always with You أحمد الغضبان
GNU G++17
180 ms
27.0 MB
Accepted