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

using namespace std;

typedef long long ll;

#define sim template <class c
#define ris return *this
#define dor > debug& operator<<
#define eni(x) sim > typename enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) {
    return rge<c>{i, j};
}
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
    ~debug() {
        cerr << endl;
    }
    eni(!=) cerr << boolalpha << i;
    ris;
} eni(==) ris << range(begin(i), end(i));
}
sim, class b dor(pair<b, c> d) {
    ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
    *this << "[";
    for (auto it = d.b; it != d.e; ++it)
        *this << ", " + 2 * (it == d.b) << *it;
    ris << "]";
}
#else
    sim dor(const c&) {
        ris;
    }
#endif
}
;
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

const int N = 1001000;
const ll INF = 1e18;

int a[N], b[N], c[N], d[N];

ll p[N];
ll dp[N];
ll best[N];

int main() {
    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= n; i++) {
        scanf("%d", a + i);
    }

    for (int i = 1; i <= n; i++) {
        scanf("%d", c + i);
        p[i] = (c[i] > 0 ? c[i] : 0) + p[i - 1];
    }

    for (int i = 1; i <= m; i++) {
        scanf("%d", b + i);
        d[b[i]] = i;
    }

    // debug() << imie(range(a + 1, a + n + 1));
    // debug() << imie(range(c + 1, c + n + 1));
    // debug() << imie(range(p + 1, p + n + 1));
    // debug() << imie(range(b + 1, b + m + 1));
    // debug() << imie(range(d + 1, d + n + 1));

    dp[0] = 0;
    best[0] = dp[0] - p[0];

    for (int x = 1; x <= n; x++) {
        best[x] = -INF;
    }

    for (int i = 1; i <= n; i++) {
        int j = d[a[i]];
        if (j > 0) {
            int x = b[j], y = b[j - 1];
            dp[i] = c[i] + p[i - 1] + best[y];
            best[x] = max(best[x], dp[i] - p[i]);
        }
    }

    // debug() << imie(range(dp, dp + n + 1));

    ll answer = -INF;
    for (int i = 1; i <= n; i++) {
        if (a[i] == b[m]) {
            answer = max(answer, dp[i] + p[n] - p[i]);
        }
    }

    ll sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += c[i];
    }

    // debug() << imie(sum) imie(answer);

    cout << sum - answer << endl;
}
Copy
Always with Me, Always with You Baraa_Armoush
GNU G++17
187 ms
34.5 MB
Accepted