#include<iostream>
#include<algorithm>
using namespace std;
int n, k, a[505], b[505], dp[505][505];
struct node {
int l, r, id;
bool operator <(node b) { return l < b.l; }
}c[505];
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++)cin >> a[i];
for (int i = 1; i <= n; i++)cin >> b[i];
for (int i = 1; i <= n; i++)c[i].r = 1e9;
for (int i = n; i >= 1; i--)c[i].l = 1e9;
for (int i = 1; i <= n; i++)c[a[i]].r = i;
for (int i = n; i >= 1; i--)c[a[i]].l = i;
for (int i = 1; i <= n; i++)c[a[i]].id = a[i];
sort(c + 1, c + n + 1);
int tail = 0;
for (int i = 1; i <= n; i++)if (c[i].l != 1e9)tail = i;
for (int i = tail; i >= 1; i--) {
dp[i][1] = b[c[i].id];
for (int j = i + 1; j <= tail; j++) {
if (c[i].r < c[j].l && c[i].id < c[j].id) {
for (int p = 2; p <= k; p++)
if (dp[j][p - 1])
dp[i][p] = max(dp[i][p], b[c[i].id] + dp[j][p - 1]);
}
}
}
int ans = 0;
for (int i = 1; i <= tail; i++)ans = max(ans, dp[i][k]);
if (ans == 0)cout << -1;
else cout << ans;
}
思路大概是,从最后往前推,用后面更新前面的