Search for a command to run...
Progressive hints first, then the full explanation and implementation when you're ready to cash out.
Review status
AI-generated and still unreviewed. Double-check the details before internalizing them.
Hints
Open only as much as you need to keep the solve alive.
Process the sequence from left to right. Once you decide the final value of , the only thing cares about is being strictly larger than that.
There is never a reason to increase an element more than necessary. Extra increases only make life harder for the next elements. Greedy isn't just okay here — it's begging to be used.
For each , if after previous fixes, do nothing. Otherwise, add some number of times until .
If the current adjusted previous value is and current value is , you need the smallest integer such that
Rearrange this with integer division.
The exact number of moves for position when is
Add to the answer and replace by .
We can only increase elements, and each operation adds exactly to one chosen element.
The sequence must satisfy:
When processing position , all earlier positions are already fixed. In particular, the only condition involving and the past is:
So we should make the smallest possible value greater than the already-fixed . Increasing it more is pure self-sabotage: it costs extra moves and makes the next element's job harder. Bad deal.
Scan from left to right.
For every from to :
We want the smallest such nonnegative integer .
If , then:
Then update:
and add to the answer.
At index , the previous value is already fixed and cannot be decreased. Therefore any valid final sequence must make the current value strictly larger than .
Choosing the minimum possible valid value for is optimal because:
So the greedy choice is locally optimal and also helps the future. That's the rare kind of greedy that doesn't stab you in the back.
We do one pass through the array, and each step does work.
time and
extra memory, ignoring the input array.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int n;
ll d;
cin >> n >> d;
vector<ll> b(n);
for (ll &x : b) cin >> x;
ll ans = 0;
for (int i = 1; i < n; i++) {
if (b[i] <= b[i - 1]) {
ll moves = (b[i - 1] - b[i]) / d + 1;
ans += moves;
b[i] += moves * d;
}
}
cout << ans << '\n';
return 0;
}#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int n;
ll d;
cin >> n >> d;
vector<ll> b(n);
for (ll &x : b) cin >> x;
ll ans = 0;
for (int i = 1; i < n; i++) {
if (b[i] <= b[i - 1]) {
ll moves = (b[i - 1] - b[i]) / d + 1;
ans += moves;
b[i] += moves * d;
}
}
cout << ans << '\n';
return 0;
}