#include #include #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; using FW = atcoder::fenwick_tree; int op(int a, int b) { return max(a, b); } int e() { return 0; } using Seg = atcoder::segtree; 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; template vector compress(vector &org, vector &compressed) { int size = org.size(); vector values(org); sort(values.begin(), values.end()); values.erase(unique(values.begin(), values.end()), values.end()); compressed.resize(size); for (int i = 0; i < size; ++i) { auto oi = org.at(i); auto it = lower_bound(values.begin(), values.end(), oi); compressed.at(i) = it - values.begin(); } return values; } bool is_ok(int N, int M, Table &D, int mid) { Table dp(N, VI1(M, 0)); for (int i = 0; i < M; ++i) dp[0][i] = 1; for (int i = 0; i < N - 1; ++i) { VI1 csum(M + 1, 0); for (int j = 0; j < M; ++j) csum.at(j + 1) = csum.at(j) + dp[i][j]; for (int j = 0, l = 0, r = 0; j < M; ++j) { auto A2 = D[i + 1][j]; auto lb = A2 - mid, ub = A2; for (; l < M; ++l) { if (lb <= D[i][l]) break; } for (; r < M; ++r) { if (ub < D[i][r]) break; } if (csum.at(r) - csum.at(l) > 0) dp[i + 1][j] = 1; } } auto max_dp = *max_element(dp[N - 1].begin(), dp[N - 1].end()); return (max_dp == 1); } 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()); } int min_D = INF, max_D = 0; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { chmin(min_D, D[i][j]); chmax(max_D, D[i][j]); } } int ok = max_D - min_D + 1; int ng = -1; while (abs(ok - ng) > 1) { auto mid = (ok + ng) / 2; if (is_ok(N, M, D, mid)) ok = mid; else ng = mid; } if (ok == max_D - min_D + 1 && !is_ok(N, M, D, ok)) return -1; return ok; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); auto result = solve(); cout << result << endl; }