#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
int vertex;
int weight;
} Edge;
typedef struct {
Edge *edges;
int size;
int capacity;
} MaxHeap;
void initHeap(MaxHeap *heap, int capacity) {
heap->edges = (Edge *)malloc(sizeof(Edge) * capacity);
heap->size = 0;
heap->capacity = capacity;
}
void swap(Edge *a, Edge *b) {
Edge temp = *a;
*a = *b;
*b = temp;
}
void heapify(MaxHeap *heap, int index) {
int largest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
if (left < heap->size && heap->edges[left].weight > heap->edges[largest].weight)
largest = left;
if (right < heap->size && heap->edges[right].weight > heap->edges[largest].weight)
largest = right;
if (largest != index) {
swap(&heap->edges[index], &heap->edges[largest]);
heapify(heap, largest);
}
}
void insertHeap(MaxHeap *heap, int vertex, int weight) {
if (heap->size >= heap->capacity) return;
heap->edges[heap->size] = (Edge){vertex, weight};
int i = heap->size;
heap->size++;
while (i > 0 && heap->edges[i].weight > heap->edges[(i - 1) / 2].weight) {
swap(&heap->edges[i], &heap->edges[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
Edge extractMax(MaxHeap *heap) {
if (heap->size == 0) return (Edge){-1, -1};
Edge root = heap->edges[0];
heap->edges[0] = heap->edges[heap->size - 1];
heap->size--;
heapify(heap, 0);
return root;
}
int manhattanDistance(int *a, int *b, int K) {
int dist = 0;
for (int i = 0; i < K; i++) {
dist += abs(a[i] - b[i]);
}
return dist;
}
int main() {
int N, K;
scanf("%d %d", &N, &K);
int points[N][K];
for (int i = 0; i < N; i++) {
for (int j = 0; j < K; j++) {
scanf("%d", &points[i][j]);
}
}
int mst[N];
for (int i = 0; i < N; i++) mst[i] = 0;
MaxHeap heap;
initHeap(&heap, N * N);
int totalCost = 0;
mst[0] = 1;
for (int i = 1; i < N; i++) {
int cost = manhattanDistance(points[0], points[i], K);
insertHeap(&heap, i, cost);
}
while (heap.size > 0) {
Edge maxEdge = extractMax(&heap);
int u = 0;
int v = maxEdge.vertex;
if (mst[v] == 0) {
totalCost += maxEdge.weight;
mst[v] = 1;
for (int i = 0; i < N; i++) {
if (mst[i] == 0) {
int cost = manhattanDistance(points[v], points[i], K);
insertHeap(&heap, i, cost);
}
}
}
}
printf("%d\n", totalCost);
return 0;
}