Source Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ss second
#define ff first
#define pb push_back
#define mp make_pair
ll n,m;
ll a[1000100],c[1000100],b[1000100],s[1000100];
ll dp[1000100],adp[1000100];
int idx[1000100],g[1000100];
int nxt1[1000100],nxt2[1000100];
ll go(int cr){
    if(dp[cr]!=-1){
        return adp[cr];
    }
    dp[cr]=0;
    ll &ret=adp[cr];
    ret=1e17;
    if(nxt2[cr]!=-1){
        ret=min(ret,s[nxt2[cr]-1]-s[cr-1]+go(nxt2[cr]));
    }
    if(nxt1[cr]!=-1){
        ret=min(ret,s[nxt1[cr]-1]-s[cr]+go(nxt1[cr]));
    }
    if(a[cr]==b[m]){
        ret=min(ret,s[n]-s[cr]);
    }
    return ret;
}
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin>>n>>m;
    memset(dp,-1,sizeof dp);
    for(int i=1;i<=n;i++){
        cin>>a[i];
     //   dp[i]=1e16;
    }
    for(int i=1;i<=n;i++){
        cin>>c[i];
        s[i]=s[i-1];
        if(c[i]<0)s[i]+=c[i];
    }
     memset(g,-1,sizeof g);
    for(int j=1;j<=m;j++){
            cin>>b[j];
            //if(j>1){
                g[b[j-1]]=b[j];
            //}
    }
    memset(idx,-1,sizeof idx);
    memset(nxt1,-1,sizeof nxt1);
    memset(nxt2,-1,sizeof nxt2);
    for(int i=n;i>=0;i--){
        if(g[a[i]]!=-1){
            nxt1[i]=idx[g[a[i]]];
        }
        nxt2[i]=idx[a[i]];
        idx[a[i]]=i;
    }
    ll ans=0;
    ans+=s[nxt1[0]-1];
    cout<<go(nxt1[0])+ans;
}
/*
5 3
1 3 3 2 4 6
-1 -5 -10 4 -3 5
1 3 2

*/
Copy
Always with Me, Always with You Wesam
GNU G++17
187 ms
64.7 MB
Accepted