1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<vector>
#include<algorithm>
#define PB push_back
#define F first
#define S second
#define ll long long
using namespace std;
constexpr int MN=1e3+17;
int tab[MN];
int main(){
ios_base::sync_with_stdio(0);
int n,k,a,last;
cin>>n>>k>>tab[1];
int s=0;
for(int j=2;j<=n;j++)
{
    last=a;
    cin>>tab[j];
    if(tab[j-1]<tab[j]){for(int t=j-1;t>0;t--) {int d=tab[t+1]-tab[t]-k; if(d>0){tab[t]+=d;s+=d;}else break;}}
    else if(tab[j-1]-tab[j]>k){int d=tab[j-1]-tab[j]-k;{s+=d;tab[j]+=d;}}
}
cout<<s<<endl;
}