#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int k;
cin >> k;
vector<int> a(n);
set<pair<int, int>> pq;
for (int i = 0; i < n; i++) {
cin >> a[i];
pq.insert({a[i], i});
}
long long result = 0;
while (!pq.empty()) {
// cout << "pq: " << endl;
// for (const auto& p : pq) {
// cout << " " << p.first << ", " << p.second << endl;
// }
auto max = prev(pq.end());
auto [maxValue, maxIndex] = *max;
pq.erase(max);
// cout << "max: " << maxValue << ", " << maxIndex << endl;
if (maxIndex > 0) {
int prev = a[maxIndex - 1];
// cout << "prev: " << prev << endl;
if (maxValue - prev > k) {
int newPrev = maxValue - k;
// cout << "newPrev: " << newPrev << endl;
result += newPrev - prev;
pq.erase({prev, maxIndex - 1});
pq.insert({newPrev, maxIndex - 1});
a[maxIndex - 1] = newPrev;
}
}
if (maxIndex < n - 1) {
int next = a[maxIndex + 1];
// cout << "next: " << next << endl;
if (maxValue - next > k) {
int newNext = maxValue - k;
// cout << "newNext: " << newNext << endl;
result += newNext - next;
pq.erase({next, maxIndex + 1});
pq.insert({newNext, maxIndex + 1});
a[maxIndex + 1] = newNext;
}
}
}
cout << result << endl;
}
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #include <iostream> #include <set> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; int k; cin >> k; vector<int> a(n); set<pair<int, int>> pq; for (int i = 0; i < n; i++) { cin >> a[i]; pq.insert({a[i], i}); } long long result = 0; while (!pq.empty()) { // cout << "pq: " << endl; // for (const auto& p : pq) { // cout << " " << p.first << ", " << p.second << endl; // } auto max = prev(pq.end()); auto [maxValue, maxIndex] = *max; pq.erase(max); // cout << "max: " << maxValue << ", " << maxIndex << endl; if (maxIndex > 0) { int prev = a[maxIndex - 1]; // cout << "prev: " << prev << endl; if (maxValue - prev > k) { int newPrev = maxValue - k; // cout << "newPrev: " << newPrev << endl; result += newPrev - prev; pq.erase({prev, maxIndex - 1}); pq.insert({newPrev, maxIndex - 1}); a[maxIndex - 1] = newPrev; } } if (maxIndex < n - 1) { int next = a[maxIndex + 1]; // cout << "next: " << next << endl; if (maxValue - next > k) { int newNext = maxValue - k; // cout << "newNext: " << newNext << endl; result += newNext - next; pq.erase({next, maxIndex + 1}); pq.insert({newNext, maxIndex + 1}); a[maxIndex + 1] = newNext; } } } cout << result << endl; } |
English