#pragma GCC target("avx2") #pragma GCC optimize("unroll-loops") #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define ALL(x) (x).begin(), (x).end() #define PC(x) __builtin_popcount(x) #define PCL(x) __builtin_popcountll(x) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair pii; typedef pair pll; template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } return false; } const double PI = 3.14159265358979323846; const double PI2 = PI * 2.0; const double EPS = 1E-09; const ll MOD = 1E+09 + 7; // =998244353; const ll INFL = 1E18; const int INFI = 1E09; const int MAX_N = 1500; struct edge { int to, cost, id; }; ll di[4] = { 0, -1, 0, 1 }, dj[4] = { 1, 0, -1, 0 }; int N, M; ll D[MAX_N + 1][MAX_N + 1]; bool check(ll x) { vector dp(M + 2, false); vector s(M + 2, 0); for (int j = 1; j <= M; ++j) { s[j] = j; } for (int i = 2; i <= N; ++i) { for (int j = 1; j <= M; ++j) { int left = lower_bound(D[i - 1] + 1, D[i - 1] + M + 1, D[i][j] - x) - D[i - 1]; int right = (int)(upper_bound(D[i - 1] + 1, D[i - 1] + M + 1, D[i][j]) - D[i - 1]); int cnt = s[right - 1] - s[left - 1]; if (cnt > 0) { dp[j] = true; } else { dp[j] = false; } } for (int j = 1; j <= M; ++j) { s[j] = (dp[j] ? 1 : 0); } for (int j = 1; j <= M; ++j) { s[j] += s[j - 1]; } } for (int j = 1; j <= M; ++j) { if (dp[j]) return true; } return false; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N >> M; for (int i = 1; i <= N; ++i) { for (int j = 1; j <= M; ++j) { cin >> D[i][j]; } sort(D[i], D[i] + M + 1); } if (N == 1) { cout << 0 << "\n"; return 0; } ll low = -1, high = INFI; while (high - low > 1) { ll mid = (low + high) / 2; if (check(mid)) { high = mid; } else { low = mid; } } // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // cout << "i = " << i << ", j = " << j << ", dp = " << dp[i][j] << "\n"; // } // } cout << (high == INFI ? -1 : high) << "\n"; return 0; }