#include <iostream>
#include <vector>
using namespace std;
bool decide(int a, int b){
return a > b;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n,k,result = 0, temp;
cin >> n >> k;
vector<int> v(n);
for(int i=0; i < n; ++i){
cin >> v[i];
}
int max = 0;
int index = 0;
for(int i = 0; i < n; ++i){
if(v[i] > max){
max = v[i];
index = i;
}
}
int i = index;
int direction = index == n-1 ? -1 : 1;
int j = i + direction;
bool changed = false;
int strike = 0;
while((i < n) && (i >= 0)){
if(decide(v[i], v[j])){
int temp = (v[i] - v[j]);
if(temp > k){
changed = true;
result += temp - k;
v[j] += temp - k;
}
} else {
int temp = (v[j] - v[i]);
if(temp > k){
changed = true;
result += temp - k;
v[i] += temp - k;
}
}
i += direction;
j = i + direction;
if(i >= n || i < 0 || j >= n || j < 0){
if(changed){
strike = 0;
changed = false;
} else {
strike++;
}
if(strike == 2){
break;
}
direction *= -1;
i += direction;
j = i + direction;
}
}
cout << result << "\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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #include <iostream> #include <vector> using namespace std; bool decide(int a, int b){ return a > b; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n,k,result = 0, temp; cin >> n >> k; vector<int> v(n); for(int i=0; i < n; ++i){ cin >> v[i]; } int max = 0; int index = 0; for(int i = 0; i < n; ++i){ if(v[i] > max){ max = v[i]; index = i; } } int i = index; int direction = index == n-1 ? -1 : 1; int j = i + direction; bool changed = false; int strike = 0; while((i < n) && (i >= 0)){ if(decide(v[i], v[j])){ int temp = (v[i] - v[j]); if(temp > k){ changed = true; result += temp - k; v[j] += temp - k; } } else { int temp = (v[j] - v[i]); if(temp > k){ changed = true; result += temp - k; v[i] += temp - k; } } i += direction; j = i + direction; if(i >= n || i < 0 || j >= n || j < 0){ if(changed){ strike = 0; changed = false; } else { strike++; } if(strike == 2){ break; } direction *= -1; i += direction; j = i + direction; } } cout << result << "\n"; return 0; } |
English