#include using namespace std; #define rep(i, a, b) for(int i=a;i<(b);++i) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long ll; typedef pair pii; typedef vector vi; using un = long long; using vuc = vector; using vol = vector; #define REP(i, a, b) for (un i = (un)a; i < (un)b; i++) #define FEAC(i, a) for (auto&& i : a) #define ALL(x) (x).begin(), (x).end() #define vec vector un N, D; vec vstup; vuc offset; vuc order; un compute_med_cost(vuc input) { sort(ALL(input)); un L = input.size(); un med = input[L/2]; un ret = 0; REP(i, 0, L) { ret += abs(input[i] - med); } return ret; } un distance(un i, un j) { un ret = 0; REP(d, 0, D) ret += abs(vstup[d][i]-vstup[d][j]); return ret; } bool is_increasing(un d){ REP(i, 0, N-1) { if (vstup[d][order[i]] > vstup[d][order[i+1]]) return false; } return true; } bool is_decreasing(un d){ REP(i, 0, N-1) { if (vstup[d][order[i]] < vstup[d][order[i+1]]) return false; } return true; } int main(){ cin.tie(0)->sync_with_stdio(0); cout.tie(0); cin >> N >> D; vstup = vec(D, vuc(N)); REP(n, 0, N) REP(d, 0, d) { cin >> vstup[d][n]; } un soucet = 0; vuc med_costs(D); REP(d, 0, D) { med_costs[d] = compute_med_cost(vstup[d]); soucet += med_costs[d]; } offset = vuc(N); offset[0] = 0; REP(n, 1, N) { offset[n] = distance(0, n); } vec> toSort; REP(n, 0, N) toSort.push_back({offset[n], n}); sort(ALL(toSort)); order = vuc(N); REP(n, 0, N) { order[n] = toSort[n].second; } REP(d, 0, D) { if (not (is_increasing(d) or is_decreasing((d)))) { cout << "-1" << endl; return 0; } } un ret = INT64_MAX; REP(d, 0, D) { REP(n, 0, N) { vstup[d][n] -= offset[n]; } ret = min(ret, soucet - med_costs[d] + compute_med_cost(vstup[d])); } cout << ret << endl; }