#include <bits/stdc++.h>
using namespace std;
int start_heights[1000010];
bool processed[1000010];
int main() {
std::ios_base::sync_with_stdio(false);
int n, k;
priority_queue<pair<int, int>> required_heights;
cin >> n >> k;
int height;
for (int i = 0; i < n; i++) {
cin >> height;
required_heights.push({height, i});
processed[i] = false;
start_heights[i] = height;
}
int result = 0;
while(!required_heights.empty()) {
auto aux = required_heights.top();
required_heights.pop();
int height = aux.first;
int pos = aux.second;
if (processed[pos]) {
continue;
}
processed[pos] = true;
result += height - start_heights[pos]; // Guaranteed to be non negative
if (pos > 0) {
required_heights.push({height - k, pos - 1});
}
if (pos < n - 1) {
required_heights.push({height - k, pos + 1});
}
}
cout << result << "\n";
}
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 | #include <bits/stdc++.h> using namespace std; int start_heights[1000010]; bool processed[1000010]; int main() { std::ios_base::sync_with_stdio(false); int n, k; priority_queue<pair<int, int>> required_heights; cin >> n >> k; int height; for (int i = 0; i < n; i++) { cin >> height; required_heights.push({height, i}); processed[i] = false; start_heights[i] = height; } int result = 0; while(!required_heights.empty()) { auto aux = required_heights.top(); required_heights.pop(); int height = aux.first; int pos = aux.second; if (processed[pos]) { continue; } processed[pos] = true; result += height - start_heights[pos]; // Guaranteed to be non negative if (pos > 0) { required_heights.push({height - k, pos - 1}); } if (pos < n - 1) { required_heights.push({height - k, pos + 1}); } } cout << result << "\n"; } |
English