#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 dp1(n * 2 - 1, vector(n * 2 - 1, 0LL)), dp2(n * 2 - 1, vector(n * 2 - 1, 0LL)); const auto make_dp2 = [&](const int l, const int r) -> void { FOR(diff, 1, k + 1) dp2[l][r] |= dp1[l][r] >> diff; dp2[l][r] |= dp1[l][r]; FOR(diff, 1, k + 1) dp2[l][r] |= dp1[l][r] << diff; }; REP(r, n * 2 - 1) { dp1[r][r] = 1LL << c[r % n]; make_dp2(r, r); for (int l = r - 1; l >= 0 && r - l + 1 <= n; --l) { FOR(m, l, r) { if (dp1[l][m] == 0 || dp1[m + 1][r] == 0) continue; dp1[l][r] |= (dp1[l][m] & dp2[m + 1][r]) | (dp2[l][m] & dp1[m + 1][r]); } make_dp2(l, r); } } ll ans = 0; REP(i, n * 2 - 1) { ll magic = 0; for (int j = i; j - i + 1 <= n && j < n * 2 - 1; ++j) { magic += a[j % n]; if (dp1[i][j] > 0) chmax(ans, magic); } } cout << ans << '\n'; return 0; }