#include using namespace std; using ll = long long; using ld = long double; using Pair = pair; using Tuple = tuple; using VI1 = vector; using VI2 = vector; using VL1 = vector; using VL2 = vector; using VD1 = vector; using VD2 = vector; using VB1 = vector; using VB2 = vector; using VP1 = vector; using VP2 = vector; using VT1 = vector; using VT2 = vector; using Queue = queue; using DQ = deque; using PQ = priority_queue, greater>; using Table = VI2; using Graph = VI2; template bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } template bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } const int INF = 1001001001; auto solve() { int N, M; cin >> N >> M; Table D(N, VI1(M)); for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) cin >> D[i][j]; sort(D.at(i).begin(), D.at(i).end()); } Table dp(N, VI1(M, INF)); for (int i = 0; i < M; ++i) dp[0][i] = 0; for (int i = 0; i < N - 1; ++i) { auto &Di = D.at(i); PQ pq1, pq2; for (int j = 0, r = 0; j < M; ++j) { auto A2 = D[i + 1][j]; for (; r < M; ++r) { if (A2 < Di[r]) break; pq1.emplace(dp[i][r], r); pq2.emplace(-Di[r], r); } while (pq1.size()) { auto [x, u] = pq1.top(); if (A2 - Di[u] <= x) { chmin(dp[i + 1][j], x); break; } pq1.pop(); } while (pq2.size()) { auto [x, u] = pq2.top(); if (dp[i][u] <= A2 + x) { chmin(dp[i + 1][j], A2 + x); break; } pq2.pop(); } } } auto min_cost = *min_element(dp[N - 1].begin(), dp[N - 1].end()); if (min_cost == INF) return -1; return min_cost; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); auto result = solve(); cout << result << endl; }