#include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define pll pair<ll,ll>
#define pii pair<int,int>
#define ld long double
using namespace std;
const int N = 1e3+1;
int h[N],n,k;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for(int i = 1;i <= n;i++)cin >> h[i];
ll total = 0;
for(int i = 1;i < n;i++){
if(h[i] - h[i+1] > k){
total += h[i] - h[i+1] - k;
h[i+1] += h[i] - h[i+1] - k;
}
if(h[i+1] - h[i] > k){
total += h[i+1] - h[i] - k;
h[i] += h[i+1] - h[i] - k;
}
}
for(int i = n;i >= 2;i--){
if(h[i] - h[i-1] > k){
total += h[i] - h[i-1] - k;
h[i-1] += h[i] - h[i-1] - k;
}
if(h[i-1] - h[i] > k){
total += h[i-1] - h[i] - k;
h[i] += h[i-1] - h[i] - k;
}
}
cout << total;
}
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 | #include<bits/stdc++.h> #define ll long long #define pb push_back #define pll pair<ll,ll> #define pii pair<int,int> #define ld long double using namespace std; const int N = 1e3+1; int h[N],n,k; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> k; for(int i = 1;i <= n;i++)cin >> h[i]; ll total = 0; for(int i = 1;i < n;i++){ if(h[i] - h[i+1] > k){ total += h[i] - h[i+1] - k; h[i+1] += h[i] - h[i+1] - k; } if(h[i+1] - h[i] > k){ total += h[i+1] - h[i] - k; h[i] += h[i+1] - h[i] - k; } } for(int i = n;i >= 2;i--){ if(h[i] - h[i-1] > k){ total += h[i] - h[i-1] - k; h[i-1] += h[i] - h[i-1] - k; } if(h[i-1] - h[i] > k){ total += h[i-1] - h[i] - k; h[i] += h[i-1] - h[i] - k; } } cout << total; } |
English