#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]; 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]; } rep(len,2,n+1){ rep(i,0,2*n+1-len){ // [i, i+len) rep(j,i+1,i+len){ rep(k,0,50){ if (dp[i][j][k] < 0) continue; rep(l,max(0,k-f),min(50,k+f+1)){ chmax(dp[i][i+len][k], dp[i][j][k] + dp[j][i+len][l]); } rep(l,max(0,k-f),min(50,k+f+1)){ chmax(dp[i][i+len][l], dp[i][j][k] + dp[j][i+len][l]); } } } } } 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'; }