Under construction

Still being built. Things may change

Hosting the Contest

Time limit1sMemory limit1024 MB

Summary
Pick one difficulty from each of N groups and order them so the sum of adjacent absolute differences is as small as possible.
Level

Medium7 of 10

Topics
Two pointers, Sliding window, Sorting
Solved
No attempts yet

Problem

Yongbeom is writing problems for Boramcup. He made KK problems for each of NN different algorithm types, so N×KN \times K problems in total. The difficulty of the jj-th problem of the ii-th algorithm is dijd_{ij}. The contest does not have time for all of them, so he will use exactly one problem from each of the NN algorithm types, NN problems in total.

Yongbeom also wants to keep the difficulty curve small so that difficulty does not jump sharply. If the difficulty of the ii-th problem in the contest is xix_i, the difficulty curve is ∣x1−x2∣+∣x2−x3∣+⋯+∣xN−1−xN∣|x_1 - x_2| + |x_2 - x_3| + \cdots + |x_{N-1} - x_N|. When N=1N = 1, the difficulty curve is defined as 00.

Help Yongbeom. Arrange the NN problems in a suitable order and find the minimum possible difficulty curve.

Input

The first line contains two integers NN and KK, the number of algorithm types and the number of problems made for each type, separated by a space. (1≤N,K≤1 000)(1 \le N, K \le 1\,000)

The next NN lines contain the difficulties. On line i+1i+1, the integers di1,⋯ ,diKd_{i1}, \cdots, d_{iK} are given, separated by spaces, where dijd_{ij} is the difficulty of the jj-th problem of the ii-th algorithm. (1≤dij≤100 000)(1 \le d_{ij} \le 100\,000)

Output

Print the minimum difficulty curve when the NN problems are arranged in a suitable order.

Examples1

  1. Example 1

    Input
    3 3
    7 2 3
    6 9 5
    1 4 3
    
    Expected output
    2