#include <iostream>
#include <vector>
#include <queue>
#include <utility>
#include <cmath>
using namespace std;
void input(int & n, int & k, vector<int> & heights) {
cin >> n >> k;
heights.resize(n);
for(int i = 0; i < n; i++) {
cin >> heights[i];
}
}
int get_necessary_gravel(int const n, int const k, vector<int> & heights) {
int result = 0;
priority_queue<pair<int, int>> heights_queue;
for(int i = 0; i < n; i++) {
heights_queue.push({heights[i], i});
}
while(!heights_queue.empty()) {
pair<int, int> cur_pair = heights_queue.top();
heights_queue.pop();
if(cur_pair.second > 0 &&
(heights[cur_pair.second] - heights[cur_pair.second-1]) > k) {
int needed_diff = heights[cur_pair.second] - heights[cur_pair.second-1] - k;
result += needed_diff;
heights[cur_pair.second-1] += needed_diff;
heights_queue.push({heights[cur_pair.second-1], cur_pair.second-1});
}
if(cur_pair.second < n-1 &&
(heights[cur_pair.second] - heights[cur_pair.second+1]) > k) {
int needed_diff = heights[cur_pair.second] - heights[cur_pair.second+1] - k;
result += needed_diff;
heights[cur_pair.second+1] += needed_diff;
heights_queue.push({heights[cur_pair.second+1], cur_pair.second+1});
}
}
return result;
}
void solve() {
int n, k;
vector<int> heights;
input(n, k, heights);
cout << get_necessary_gravel(n, k, heights) << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
solve();
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 50 51 52 53 54 55 56 57 58 59 60 | #include <iostream> #include <vector> #include <queue> #include <utility> #include <cmath> using namespace std; void input(int & n, int & k, vector<int> & heights) { cin >> n >> k; heights.resize(n); for(int i = 0; i < n; i++) { cin >> heights[i]; } } int get_necessary_gravel(int const n, int const k, vector<int> & heights) { int result = 0; priority_queue<pair<int, int>> heights_queue; for(int i = 0; i < n; i++) { heights_queue.push({heights[i], i}); } while(!heights_queue.empty()) { pair<int, int> cur_pair = heights_queue.top(); heights_queue.pop(); if(cur_pair.second > 0 && (heights[cur_pair.second] - heights[cur_pair.second-1]) > k) { int needed_diff = heights[cur_pair.second] - heights[cur_pair.second-1] - k; result += needed_diff; heights[cur_pair.second-1] += needed_diff; heights_queue.push({heights[cur_pair.second-1], cur_pair.second-1}); } if(cur_pair.second < n-1 && (heights[cur_pair.second] - heights[cur_pair.second+1]) > k) { int needed_diff = heights[cur_pair.second] - heights[cur_pair.second+1] - k; result += needed_diff; heights[cur_pair.second+1] += needed_diff; heights_queue.push({heights[cur_pair.second+1], cur_pair.second+1}); } } return result; } void solve() { int n, k; vector<int> heights; input(n, k, heights); cout << get_necessary_gravel(n, k, heights) << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); solve(); return 0; } |
English