#include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 998244353; // constexpr int MOD = 1000000007; constexpr int DY4[]{1, 0, -1, 0}, DX4[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}; constexpr int DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; int main() { constexpr int C = 50; int n, k; cin >> n >> k; vector a(n), c(n); REP(i, n) cin >> a[i]; REP(i, n) cin >> c[i], --c[i]; vector dp(n * 2 - 1, vector(n * 2 - 1, 0LL)); REP(r, n * 2 - 1) { dp[r][r] = 1LL << c[r % n]; for (int l = r - 1; l >= 0 && r - l + 1 <= n; --l) { FOR(m, l, r) { if (dp[m + 1][r] == 0) continue; for (ll index = dp[l][m]; index > 0;) { const uint64_t lsb = index & -index; const int i = countr_zero(lsb); for (int j = max(i - k, 0); j <= i + k && j < C; ++j) { if (dp[m + 1][r] >> j & 1) dp[l][r] |= (1LL << i) | (1LL << j); } index ^= lsb; } } } } ll ans = 0; REP(i, n * 2 - 1) { ll magic = 0; for (int j = i; j - i + 1 <= n; ++j) { magic += a[j % n]; if (dp[i][j] > 0) chmax(ans, magic); } } cout << ans << '\n'; return 0; }