#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[700][700][52]; ll val[52]; int x[600], y[600]; 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[j][k][i] = -1e18; } } } rep(i,0,2*n){ dp[i][i+1][c[i]] = a[i]; } int m = 0; rep(k,0,50){ rep(l,max(0,k-f),min(50,k+f+1)){ x[m] = k; y[m] = l; m++; } } rep(len,2,n+1){ rep(i,0,2*n+1-len){ rep(k,0,50){ val[k] = -1e18; } rep(j,i+1,i+len){ rep(l,0,m){ ll v = dp[i][j][x[l]] + dp[j][i+len][y[l]]; chmax(val[x[l]], v); chmax(val[y[l]], v); } } rep(k,0,50){ dp[i][i+len][k] = val[k]; } } } ll ans = -1e18; rep(i,0,50){ rep(j,0,2*n){ rep(k,0,2*n+1){ chmax(ans, dp[j][k][i]); } } } cout << ans << '\n'; }