#include using namespace std; using ll=long long; using pll=pair; using tll=tuple; using ld=long double; const ll INF=(1ll<<60); #define rep(i,n) for (ll i=0;i<(ll)(n);i++) #define all(v) v.begin(),v.end() template void chmin(T &a,T b){ if(a>b){ a=b; } } template void chmax(T &a,T b){ if(a> n >> k; vector a(n),c(n); rep(i,n) cin >> a[i]; rep(i,n) cin >> c[i]; vector>> dp(n,vector>(n,vector(51,-INF))); rep(i,n) dp[i][i][c[i]]=a[i]; rep(l,n){ rep(r,n){ rep(x,51){ for(ll y=max(0ll,x-k);y<=min(50ll,x+k);y++){ for(ll z=l;z!=r;z=(z+1)%n){ chmax(dp[l][r][x],dp[l][z][x]+dp[(z+1)%n][r][y]); chmax(dp[l][r][x],dp[l][z][y]+dp[(z+1)%n][r][x]); } } } } } ll ans=0; rep(i,n){ rep(j,n){ rep(kk,51){ chmax(ans,dp[i][j][kk]); } } } cout << ans << '\n'; }