#include<bits/stdc++.h> #define MAX_N 1000000 #define mid ((s+t)>>1) usingnamespace std; typedeflonglong lnt; template <classT> inlinevoidread(T &x){ x = 0; int c = getchar(), f = 1; for (; !isdigit(c); c = getchar()) if (c == 45) f = -1; for (; isdigit(c); c = getchar()) (x *= 10) += f*(c-'0'); } int n, m, f[MAX_N+5], w[MAX_N+5]; int pos[MAX_N+5], nxt[MAX_N+5], cnt[MAX_N+5]; lnt tr[MAX_N<<2], tag[MAX_N<<2], ans; voidupdate(int v){tr[v] = max(tr[v<<1], tr[v<<1|1]);} voiddowntag(int v){ if (!tag[v]) return; tr[v<<1] += tag[v], tr[v<<1|1] += tag[v]; tag[v<<1] += tag[v], tag[v<<1|1] += tag[v]; tag[v] = 0; } voidmodify(int v, int s, int t, int l, int r, lnt x){ if (s >= l && t <= r) {tr[v] += x, tag[v] += x; return;} downtag(v); if (l <= mid) modify(v<<1, s, mid, l, r, x); if (r >= mid+1) modify(v<<1|1, mid+1, t, l, r, x); update(v); } intmain(){ read(n), read(m); for (int i = 1; i <= n; i++) read(f[i]); for (int i = 1; i <= m; i++) read(w[i]); for (int i = n; i; i--) nxt[i] = pos[f[i]], pos[f[i]] = i; for (int i = 1; i <= m; i++) if (pos[i]) { if (!nxt[pos[i]]) modify(1, 1, n, pos[i], n, w[i]); elsemodify(1, 1, n, pos[i], nxt[pos[i]]-1, w[i]); } for (int i = 1; i <= n; i++) { ans = max(ans, tr[1]); if (nxt[i]) { modify(1, 1, n, i, nxt[i]-1, -w[f[i]]); if (!nxt[nxt[i]]) modify(1, 1, n, nxt[i], n, w[f[i]]); elsemodify(1, 1, n, nxt[i], nxt[nxt[i]]-1, w[f[i]]); } elsemodify(1, 1, n, i, n, -w[f[i]]); } returnprintf("%lld\n", ans), 0; }