#include using namespace std; #ifdef _RUTHEN #include #else #define show(...) true #endif using ll = long long; #define rep(i, n) for (int i = 0; i < (n); i++) template using V = vector; int main() { ios::sync_with_stdio(false); cin.tie(0); int N, M; cin >> N >> M; V> D(N, V(M)); rep(i, N) { rep(j, M) cin >> D[i][j]; sort(D[i].begin(), D[i].end()); } const ll INF = 1LL << 60; V dp(M, 0); rep(i, N - 1) { V>> G(M + 1); rep(j, M) { int lb = lower_bound(D[i + 1].begin(), D[i + 1].end(), D[i][j]) - D[i + 1].begin(); G[lb].push_back({1, j}); int ub = lower_bound(D[i + 1].begin(), D[i + 1].end(), D[i][j] + dp[j]) - D[i + 1].begin(); G[ub].push_back({2, j}); G[ub].push_back({3, j}); } V np(M); multiset S1; ll S2 = INF; S1.insert(INF); rep(j, M) { for (auto [t, k] : G[j]) { if (t == 1) { S1.insert(dp[k]); } else if (t == 2) { S1.extract(dp[k]); } else { S2 = min(S2, -D[i][k]); } } np[j] = min({*S1.begin(), D[i + 1][j] + S2, INF}); } swap(dp, np); } ll ans = *min_element(dp.begin(), dp.end()); if (ans == INF) ans = -1; cout << ans << '\n'; return 0; }