#include <iostream>
#include <vector>
#include <algorithm>
bool Update(std::vector<int>& a, long long& result, int k) {
std::vector<int> temp(a);
for (int i = 0; i < temp.size()-1; i++) {
if ((temp[i + 1] - temp[i] > k)) {
result += temp[i + 1] - (temp[i]+k);
temp[i] = temp[i + 1] - k;
}
}
for (int i = a.size() - 1; i > 0; i--) {
if ((temp[i - 1] - temp[i] > k)) {
result += temp[i - 1] - (temp[i] + k);
temp[i] = temp[i - 1] - k;
}
}
if (temp == a) {
a = temp;
return true;
}
a = temp;
return false;
}
int main() {
short n;
int k;
long long result = 0;
std::cin >> n >> k;
std::vector<int> a(n);
std::cin >> a[0];
for (int i = 1; i < n; i++) {
std::cin >> a[i];
}
while (!Update(a, result, k));
std::cout << result;
}
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 | #include <iostream> #include <vector> #include <algorithm> bool Update(std::vector<int>& a, long long& result, int k) { std::vector<int> temp(a); for (int i = 0; i < temp.size()-1; i++) { if ((temp[i + 1] - temp[i] > k)) { result += temp[i + 1] - (temp[i]+k); temp[i] = temp[i + 1] - k; } } for (int i = a.size() - 1; i > 0; i--) { if ((temp[i - 1] - temp[i] > k)) { result += temp[i - 1] - (temp[i] + k); temp[i] = temp[i - 1] - k; } } if (temp == a) { a = temp; return true; } a = temp; return false; } int main() { short n; int k; long long result = 0; std::cin >> n >> k; std::vector<int> a(n); std::cin >> a[0]; for (int i = 1; i < n; i++) { std::cin >> a[i]; } while (!Update(a, result, k)); std::cout << result; } |
English