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

#define ll long long
#define pb push_back
#define x first
#define y second
#define sz(u) (int)(u.size())
#define ld long double
#define all(u) u.begin(),u.end()

using namespace std;


int main()
{
	ios::sync_with_stdio(0); cin.tie(0);
	int n,m; cin>>n>>m;
	vector<ll> a(n),c(n),b(m),pos(n+1,-1),pre(n);
	for(int i=0;i<n;i++) cin>>a[i];
	for(int i=0;i<n;i++){
		cin>>c[i];
		pre[i]=min(0LL,c[i])+(i==0?0LL:pre[i-1]);
	}
	for(int i=0;i<m;i++){
		cin>>b[i];
		pos[b[i]]=i;
	}
	vector<ll> dp(n+1,1e15);
	ll ans=0;
	for(int i=0;i<n;i++){
		if(pos[a[i]]==-1) continue;
		ll tmp = (pos[a[i]]==0?0LL:dp[b[ pos[a[i]] - 1 ]])+(i==0?0LL:pre[i-1]);
		if(a[i]==b[m-1]){
			ans = min(ans,tmp+pre[n-1]-pre[i]);
		}
		dp[a[i]] = min(dp[a[i]], tmp-pre[i]);
	}
	cout<<ans<<'\n';
	return 0;
}
//bdiufbuifbr
Copy
Always with Me, Always with You medk
GNU G++17
183 ms
38.1 MB
Accepted