#include <bits/stdc++.h>
int main(){
using namespace std;
ios::sync_with_stdio(false), cin.tie(nullptr);
int n, k;
cin >> n >> k; // |a[i]-a[i+1]| <= k
vector<int> a(n);
for(int &A : a){
cin >> A;
}
// start from max and do fixing
set<pair<int, int>> S;
for(int i = 0;i < n;i++) {
S.emplace(a[i], i);
}
int64_t ans = 0;
while(!S.empty()){
auto it = prev(S.end());
int nxt = it->second + 1;
int prv = it->second - 1;
int val = it->first;
S.erase(it); // Java muscle-memory
if(nxt < n && val - a[nxt] > k){
int add = val - a[nxt] - k;
S.erase({a[nxt], nxt});
ans += add;
a[nxt] += add;
S.insert({a[nxt], nxt});
}
if(prv >= 0 && val - a[prv] > k){
int add = val - a[prv] - k;
S.erase({a[prv], prv});
ans += add;
a[prv] += add;
S.insert({a[prv], prv});
}
}
cout << ans << '\n';
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #include <bits/stdc++.h> int main(){ using namespace std; ios::sync_with_stdio(false), cin.tie(nullptr); int n, k; cin >> n >> k; // |a[i]-a[i+1]| <= k vector<int> a(n); for(int &A : a){ cin >> A; } // start from max and do fixing set<pair<int, int>> S; for(int i = 0;i < n;i++) { S.emplace(a[i], i); } int64_t ans = 0; while(!S.empty()){ auto it = prev(S.end()); int nxt = it->second + 1; int prv = it->second - 1; int val = it->first; S.erase(it); // Java muscle-memory if(nxt < n && val - a[nxt] > k){ int add = val - a[nxt] - k; S.erase({a[nxt], nxt}); ans += add; a[nxt] += add; S.insert({a[nxt], nxt}); } if(prv >= 0 && val - a[prv] > k){ int add = val - a[prv] - k; S.erase({a[prv], prv}); ans += add; a[prv] += add; S.insert({a[prv], prv}); } } cout << ans << '\n'; return 0; } |
English