#include using namespace std; #define EPS (1e-10) #define REP (i,n) for (int i = 0; i<(n);i++) typedef long double ld; typedef long long ll; typedef pair ii; typedef pair dd; typedef vector vi; typedef vector vll; typedef vector vd; int main() { ios::sync_with_stdio(false); int N, a; cin >> N >> a; vi V(N); for(int i = 0; i < N; ++i) cin >> V[i]; sort(V.begin(), V.end()); // while(lb <= ub) { // int mid = (lb+ub)/2; // ll c1 = 0, c2 = 0; // for(int i = 0; i < N; ++i) { // if (V[i] > mid + i*a) c1++; // else if (V[i] < mid + i*a) c2++; // } // if (c1 == c2) { // res = mid; // break; // } else if (c1 < c2) { // ub = mid-1; // } else { // lb = mid+1; // } // } // ll ss = 0; // // cout << res << endl; int lb = V[0], ub = V[N-1]; while (ub-lb >= 3) { int aa = lb+(ub-lb)/3; int ab = ub-(ub-lb)/3; long long s1=0, s2=0; for(int i = 0; i < N; ++i) { s1 += abs(V[i] - aa-i*a); } for(int i = 0; i < N; ++i) { s2 += abs(V[i] - ab-i*a); } if (s1 > s2) lb = aa; else ub = ab; } // cout << lb << " " << ub << endl; ll res = LLONG_MAX; for(int r = lb-3; r <= ub+3; ++r) { ll s2 = 0; for(int i = 0; i < N; ++i) { s2 += abs(V[i] - r-i*a); } res = min(s2, res); } cout << res << endl; }