#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int main() {
int N, M;
cin >> N >> M;
vector<int> heights(N);
for (int i = 0; i < N; i++) {
cin >> heights[i];
}
// dp[i][mods] = maximum height we can reach at pole i using exactly 'mods' modifications
vector<vector<int>> dp(N + 1, vector<int>(N + 1, -1));
// Base case: we start at height 0 before any pole
dp[0][0] = 0;
for (int i = 1; i <= N; i++) {
int currentHeight = heights[i - 1];
for (int mods = 0; mods <= min(i, N); mods++) {
// Option 1: Don't modify this pole
for (int prevMods = 0; prevMods <= mods && prevMods < i; prevMods++) {
if (dp[i - 1][prevMods] != -1) {
int prevHeight = dp[i - 1][prevMods];
// Can we jump to currentHeight from prevHeight?
if (currentHeight <= prevHeight + M) { // Can jump up at most M, down any amount
dp[i][mods] = max(dp[i][mods], currentHeight);
}
}
}
// Option 2: Modify this pole (use one more modification)
if (mods > 0) {
for (int prevMods = 0; prevMods < mods && prevMods < i; prevMods++) {
if (dp[i - 1][prevMods] != -1) {
int prevHeight = dp[i - 1][prevMods];
// If we modify this pole, we can set it to any height from 0 to prevHeight + M
// Best strategy: set it to prevHeight + M to maximize future reach
int optimalHeight = prevHeight + M;
dp[i][mods] = max(dp[i][mods], optimalHeight);
}
}
}
}
}
// Find the minimum number of modifications needed
for (int mods = 0; mods <= N; mods++) {
if (dp[N][mods] != -1) {
cout << mods << endl;
return 0;
}
}
// Should never reach here if input is valid
cout << N << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |