#include <bits/stdc++.h>
#define F first
#define S second
#define pii pair<int, int>
using namespace std;
using ll = long long;
using ld = long double;
constexpr int SIZE = 1e3+3;
int tab[SIZE];
int k;
ll res;
void CHECK(int v){
if (!v) return;
if (tab[v]+k >= tab[v+1]) return;
res += tab[v+1]-tab[v]-k;
tab[v] = tab[v+1]-k;
CHECK(v-1);
return;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n >> k;
for (int i=1; i<=n; i++) cin >> tab[i];
res = 0;
for (int i=1; i<n; i++){
if (tab[i]+k >= tab[i+1] && tab[i]-k <= tab[i+1]) continue;
if (tab[i]+k < tab[i+1]) CHECK(i);
else {
res += tab[i]-tab[i+1]-k;
tab[i+1] = tab[i]-k;
}
}
cout << res;
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 | #include <bits/stdc++.h> #define F first #define S second #define pii pair<int, int> using namespace std; using ll = long long; using ld = long double; constexpr int SIZE = 1e3+3; int tab[SIZE]; int k; ll res; void CHECK(int v){ if (!v) return; if (tab[v]+k >= tab[v+1]) return; res += tab[v+1]-tab[v]-k; tab[v] = tab[v+1]-k; CHECK(v-1); return; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n >> k; for (int i=1; i<=n; i++) cin >> tab[i]; res = 0; for (int i=1; i<n; i++){ if (tab[i]+k >= tab[i+1] && tab[i]-k <= tab[i+1]) continue; if (tab[i]+k < tab[i+1]) CHECK(i); else { res += tab[i]-tab[i+1]-k; tab[i+1] = tab[i]-k; } } cout << res; return 0;} |
English