Source Code
#include<bits/stdc++.h>
#define GO ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef pair<int, int> pi;
const ll Mod = 998244353;
const ll INF = (ll)(1e18) + 5;
const ll N = 1e6 + 5, M = 18;

int n, m;
int a[N], cost[N], b[N];
map<int, int> idx;

int main() {
	GO;
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	for (int i = 1; i <= n; i++)
		cin >> cost[i];
	for (int i = 1; i <= m; i++)
		cin >> b[i], idx[b[i]] = i;
	ll sum = 0;
	vec dp(m + 1, -INF);
	dp[0] = 0;
	ll ALL = 0;
	for (int i = 1; i <= n; i++) {
		ALL += cost[i];
		int x = a[i];
		int j = (idx.count(x) ? idx[x] : -1);
		if (j == -1 || dp[j - 1] == -INF) {
			if (cost[i] > 0)
				sum += cost[i];
			continue;
		}
		assert(dp[j] >= -INF);
		ll cur = dp[j - 1];
		cur += cost[i];
		if (dp[j] > -INF && cost[i] > 0)
			dp[j] += cost[i];
		dp[j] = max(dp[j], cur);
	}
	assert(ALL - (sum + dp[m]) <= 0);
	cout << ALL - (sum + dp[m]) << '\n';
	return 0;
}
Copy
Always with Me, Always with You Oxygen
GNU G++17
563 ms
24.0 MB
Wrong Answer