// Codeforces Round #177 (Div. 2) B Polo the Penguin and Matrix
import java.io.*;
import java.io.ObjectInputStream.GetField;
import java.math.*;
import java.text.*;
import java.util.*;
//Codeforces
public class MainCodeforces1 {
private static MyScanner in;
private static PrintStream out;
public static void main(String[] args) throws IOException {
// helpers for input/output
boolean LOCAL_TEST = false;// change to false before submitting
out = System.out;
if (LOCAL_TEST) {
in = new MyScanner("E:\\zin2.txt");
}
else {
boolean usingFileForIO = false;
if (usingFileForIO) {
// using input.txt and output.txt as I/O
in = new MyScanner("input.txt");
out = new PrintStream("output.txt");
}
else {
in = new MyScanner();
out = System.out;
}
}
solve();
}
private static void solve() throws IOException
{
int n = in.nextInt();
int m = in.nextInt();
int d = in.nextInt();
int[] a = new int[n * m];
for (int i = 0; i < n * m; i++) {
a[i] = in.nextInt();
}
int rem = a[0] % d;
for (int i = 0; i < n * m; i++) {
if (a[i] % d != rem) {
out.println(-1);
return;
}
}
Arrays.sort(a);
int target = a[0];
int cost;
int costNeg = 0;
int costPos = 0;
for (int i = 1; i < n * m; i++) {
costPos += (a[i] - a[0]) / d;
}
cost = costPos;
int minCost = cost;
for (int i = 1; i < n * m; i++) {
if (a[i] == a[i - 1])
continue;
int diff = a[i] - a[i - 1];
costNeg += diff / d * i;
costPos -= diff / d * (n * m - i);
cost = costPos + costNeg;
minCost = Math.min(minCost, cost);
}
out.println(minCost);
}
// =====================================
static class MyScanner {
Scanner inp = null;
public MyScanner() throws IOException
{
inp = new Scanner(System.in);
}
public MyScanner(String inputFile) throws IOException {
inp = new Scanner(new FileInputStream(inputFile));
}
public int nextInt() throws IOException {
return inp.nextInt();
}
public long nextLong() throws IOException {
return inp.nextLong();
}
public double nextDouble() throws IOException {
return inp.nextDouble();
}
public String nextString() throws IOException {
return inp.next();
}
}
}
No comments:
Post a Comment