#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 a,c; vector>> dp; ll f(ll x,ll l,ll r){ if(dp[x][l][r]!=-1) return dp[x][l][r]; if(l==r){ if(x==c[l]) return dp[x][l][r]=a[l]; else return dp[x][l][r]=-INF; } dp[x][l][r]=-INF; for(ll y=max(0ll,x-k);y<=min(50ll,x+k);y++){ for(ll k=l;k!=r;k=(k+1)%n){//yabai chmax(dp[x][l][r],f(x,l,k)+f(y,(k+1)%n,r)); chmax(dp[x][l][r],f(y,l,k)+f(x,(k+1)%n,r)); } } return dp[x][l][r]; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> k; a.resize(n); c.resize(n); rep(i,n) cin >> a[i]; rep(i,n) cin >> c[i]; dp.resize(51); rep(i,51){ dp[i].resize(n); rep(j,n){ dp[i][j].resize(n,-1); } } ll ans=0; rep(i,51){ rep(j,n){ rep(k,n){ chmax(ans,f(i,j,k)); } } } cout << ans << '\n'; }