#include #include #include #include #include #include #include #include using namespace std; typedef long long int ll; typedef pair Pii; const ll mod = 998244353; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, k; cin >> n >> k; vector a(n); for (auto &x: a) cin >> x; vector c(n); for (auto &x: c) cin >> x; vector>> dp(n, vector>(n, vector(51, -1000000000))); for (int i = 0; i < n; i++) dp[i][i][c[i]] = a[i]; for (int l = 1; l <= n; l++) { for (int i = 0; i < n; i++) { int j = i + l; for (int p = i + 1; p < j; p++) { for (int x = 1; x <= 50; x++) { for (int y = max(1, x - k); y <= min(50, x + k); y++) { dp[i][(j-1)%n][x] = max(dp[i][(j-1)%n][x], dp[i][(p-1)%n][x] + dp[p%n][(j-1)%n][y]); dp[i][(j-1)%n][y] = max(dp[i][(j-1)%n][y], dp[i][(p-1)%n][x] + dp[p%n][(j-1)%n][y]); } } } } } ll ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int x = 1; x <= 50; x++) { ans = max(ans, dp[i][j][x]); } } } cout << ans << endl; return 0; }