Source Code
#include <bits/stdc++.h>
#define ll long long
#define X first
#define Y second
#define sz(x) (int)((x).size())
#define all(x) x.begin(), x.end()
#define pii pair<int, int>

using namespace std;
mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count());

typedef vector<int> vi;
typedef vector<pii> vii;
typedef pair<int, pair<int, int>> iii;
typedef vector<unsigned int> vui;
typedef vector<ll> vll;
typedef vector<double> vd;
typedef vi vm;
typedef vector<vm> Mat;


int main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#else
    //    freopen("outofplace.in", "r", stdin);
//    freopen("outofplace.out", "w", stdout);
#endif
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0), cout.precision(10), cout << fixed;

    int n, m; cin >> n >> m;
    vll a(n), cost(n), b(m);
    for (int i = 0; i < n; ++i) cin >> a[i];
    ll ans = 0;
    for (int i = 0; i < n; ++i) {
        cin >> cost[i];
        if (cost[i] > 0) cost[i] = 0;
        ans += cost[i];
    }
    for (int i = 0; i < m; ++i) cin >> b[i];
    vi nxt(n + 1);
    for (int i = 0; i < m - 1; ++i) {
        nxt[b[i]] = b[i + 1];
    }

    vll dp(n + 1, LLONG_MAX);
    dp[b.back()] = LLONG_MIN;
    for (int i = n - 1; ~i; --i) {
        if (a[i] == b.back()) dp[a[i]] = max(dp[a[i]], cost[i]);
        if (nxt[a[i]] == 0) continue;
        if (dp[nxt[a[i]]] == LLONG_MAX) continue;
        if (dp[a[i]] == LLONG_MAX) dp[a[i]] = LLONG_MIN;
        dp[a[i]] = max(dp[a[i]], dp[nxt[a[i]]] + cost[i]);
    }

    cout << ans - dp[b[0]] << '\n';


    return 0;
}
Copy
Always with Me, Always with You Luka
GNU G++17
154 ms
27.0 MB
Wrong Answer