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
#include <cstdio>

using namespace std;

int n;
int k;
int a[1002];
bool checked[1002];
int pos;
int res;

int main() {
  // read data
  scanf("%d %d", &n, &k);

  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    checked[i] = false;
  }

  res = 0;

  for (int i = 0; i < n; i++) {
    // find the highest (could be faster, but with these time limits it doesn't matter :) )
    pos = -1;
    for (int j = 0; j < n; j++) {
      if (checked[j] == false) {
        if ((pos == -1) || (a[j] > a[pos])) {
          pos = j;
        }
      }
    }

    // apply gravel
    if (pos > 0) {
      if (a[pos] > a[pos - 1] + k) {
        res = res + a[pos] - a[pos - 1] - k;
        a[pos - 1] = a[pos] - k;
      }
    }
    if (pos < n - 1) {
      if (a[pos] > a[pos + 1] + k) {
        res = res + a[pos] - a[pos + 1] - k;
        a[pos + 1] = a[pos] - k;
      }
    }
    checked[pos] = true;
  }

  // output data
  printf("%d\n", res);

  return 0;
}