/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sutaz; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; /** * * @author janotka1 */ public class Marathon { static class Stand implements Comparable { public int distanceTotal = 0; public int value = 0; public Stand(int distanceTotal, int value) { this.distanceTotal = distanceTotal; this.value = value; } @Override public int compareTo(Stand o) { if(o.value < this.value) { return 1; } else { return -1; } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextInt()) { int stands = sc.nextInt(); int distance = sc.nextInt(); int sum = 0; Stand[] arayOfStands = new Stand[stands]; for (int i = 0; i < stands; i++) { int pos = sc.nextInt(); arayOfStands[i] = new Stand(0, pos); for (int j = 0; j < stands; j++) { if (arayOfStands[j] != null) { arayOfStands[j].distanceTotal += Math.abs(arayOfStands[j].value - arayOfStands[i].value); arayOfStands[i].distanceTotal += Math.abs(arayOfStands[j].value - arayOfStands[i].value); } } } int avg = sum / stands; Arrays.sort(arayOfStands); sumOfChange(arayOfStands, avg, distance); } } public static void sumOfChange(Stand[] arayOfStands, int avg, int distance) { int indexOfClose = 0; int min = Integer.MAX_VALUE; for (int i = 0; i < arayOfStands.length; i++) { int minCu = arayOfStands[i].distanceTotal; if (minCu < min) { min = minCu; indexOfClose = i; } } int minSum = Integer.MAX_VALUE; int sum = 0; int countBG = 0; int countSM = 0; for (int j = 0; j < arayOfStands.length; j++) { if (arayOfStands[indexOfClose].value < arayOfStands[j].value) { countSM++; sum += arayOfStands[j].value - (countSM * distance + arayOfStands[indexOfClose].value); } if (arayOfStands[indexOfClose].value > arayOfStands[j].value) { countBG++; sum += (arayOfStands[indexOfClose].value - countBG * distance) - arayOfStands[j].value; } } System.out.println(sum); } }