#pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include using namespace std; typedef long long ll; #define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++) #define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--) template bool chmin(T &a, const T &b) { if (a <= b) return false; a = b; return true; } template bool chmax(T &a, const T &b) { if (a >= b) return false; a = b; return true; } template T max(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]); return ret; } template T min(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]); return ret; } template T sum(vector &a){ T ret = 0; for (int i=0; i<(int)a.size(); i++) ret += a[i]; return ret; } ll dp[52][700][700]; ll g[52]; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n, f; cin >> n >> f; vector a(2*n); vector c(2*n); rep(i,0,n){ cin >> a[i]; a[i+n] = a[i]; } rep(i,0,n){ cin >> c[i]; c[i]--; c[i+n] = c[i]; } rep(i,0,50){ rep(j,0,2*n){ rep(k,0,2*n+1){ dp[i][j][k] = -1e18; } } } rep(i,0,2*n){ dp[c[i]][i][i+1] = a[i]; } rep(len,2,n+1){ rep(i,0,2*n+1-len){ // [i, i+len) rep(j,i+1,i+len){ { int ls = 0, rs = 0; rep(l,0,min(50,f+1)){ while (ls < rs && dp[g[rs-1]][j][i+len] <= dp[l][j][i+len]) rs--; g[rs] = l; rs++; } rep(k,0,50){ chmax(dp[k][i][i+len], dp[k][i][j] + dp[g[ls]][j][i+len]); if (ls < rs && g[ls] == k-f) ls++; if (k+f+1 < 50){ while (ls < rs && dp[g[rs-1]][j][i+len] <= dp[k+f+1][j][i+len]) rs--; g[rs] = k+f+1; rs++; } } } { int ls = 0, rs = 0; rep(l,0,min(50,f+1)){ while (ls < rs && dp[g[rs-1]][i][j] <= dp[l][i][j]) rs--; g[rs] = l; rs++; } rep(k,0,50){ chmax(dp[k][i][i+len], dp[k][j][i+len] + dp[g[ls]][i][j]); if (ls < rs && g[ls] == k-f) ls++; if (k+f+1 < 50){ while (ls < rs && dp[g[rs-1]][i][j] <= dp[k+f+1][i][j]) rs--; g[rs] = k+f+1; rs++; } } } } } } ll ans = -1e18; rep(i,0,50){ rep(j,0,2*n){ rep(k,0,2*n+1){ chmax(ans, dp[i][j][k]); } } } cout << ans << '\n'; }