Source Code
//fold
#include <bits/stdc++.h>
#define endl '\n'
#define mp make_pair
#define tostr(x) static_cast<ostringstream&>((ostringstream()<<dec<<x)).str()
#define rep(i,begin,end) for(auto i = begin;i < end;i++)
#define repr(i,begin,end) for(auto i = begin-1;i >= end;i--)
#define pb push_back
#define sz(a) ((int)(a).size())
#define fi first
#define se second
#define abs(a) ((a) < (0) ? (-1)*(a) : (a))
#define SQ(a) ((a)*(a))
#define eqd(a,b) (abs(a-b)<1e-9)
#define X real()
#define Y imag()
using namespace std;
typedef long long ll;
typedef long double ld;
template <typename t> t in(t q){cin >> q;return q;}
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v){os << "[";for (int i = 0; i < sz(v); ++i) { os << v[i]; if (i != sz(v) - 1) os << ",";}os << "]";return os;}
template <typename T, typename S>ostream& operator<<(ostream& os, const map<T, S>& v){for (auto it : v)os << "(" << it.first << ":" << it.second << ")";return os;}
template <typename T, typename S>ostream& operator<<(ostream& os, const pair<T, S>& v){os << "(" << v.first << "," << v.second << ")";return os;}
const long double PI = acosl(-1);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());
inline int rand(int l,int r){return uniform_int_distribution<int>(l, r)(rng);}
inline ll rand(ll l,ll r){return uniform_int_distribution<ll>(l, r)(rng64);}
//endfold
#define  N  (1000'005)
#define MOD (1000000000ll + 7ll)
#define OO (1050000000)
#define OOL (1100000000000000000)

//global
int a[N], b[N], c[N];

set<int> bs;
map<int,int> b_to_i;
vector<int> v[N];

ll dp[N];

int next(int i, int p){
	auto x = upper_bound(v[i+1].begin(), v[i+1].end(), p);
	if(x == v[i+1].end()) return N;
	return x-v[i+1].begin();
}

int main(){
	//fold
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cout << setprecision(10);
	//endfold
	int n,m;
	cin >> n >> m;
	rep(i,0,n){
		cin >> a[i];
	}
	rep(i,0,n){
		cin >> c[i];
	}
	rep(i,0,m){
		cin >> b[i];
		bs.insert(b[i]);
		b_to_i[b[i]] = i;
	}
	ll ans = 0;
	rep(i,0,n){
		if(!bs.count(a[i])){
			a[i] = 0;
			ans += min(0,c[i]);
		}else{
			v[b_to_i[a[i]]].push_back(i);
		}
	}
	vector<int> ind = {n};
	vector<ll> bes = {0};
	for(int i = m-1; i >= 0; i--){
		ll tc = 0;
		for(auto j: v[i]){
			tc += min(0, c[j]);
		}
		vector<ll> vid;
		for(auto j: v[i]){
			ll cc = tc-min(0, c[j]);
			auto x = upper_bound(ind.begin(), ind.end(), j)-ind.begin();
			if(x == sz(ind)){
				vid.push_back(OO);
				continue;
			}
			vid.push_back(cc+bes[x]);
		}
		for(int j = sz(vid)-1; j >= 0; j--){
			if(j+1 != sz(vid)){
				vid[j] = min(vid[j+1],vid[j]);
			}
		}
		ind = v[i];
		bes = vid;
	}
	cout << bes[0]+ans;
	return 0;
}

Copy
Always with Me, Always with You Adhami
GNU G++17
1055 ms
67.5 MB
Accepted