#include #include #include #include #include #include #include #include #include #include #include #include #include #define repeat(i,n) for (int i = 0; (i) < (n); ++(i)) #define repeat_from(i,m,n) for (int i = (m); (i) < (n); ++(i)) #define repeat_reverse(i,n) for (int i = (n)-1; (i) >= 0; --(i)) #define repeat_from_reverse(i,m,n) for (int i = (n)-1; (i) >= (m); --(i)) #define dump(x) cerr << #x << " = " << (x) << endl #define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl typedef long long ll; using namespace std; template bool setmax(T & l, T const & r) { if (not (l < r)) return false; l = r; return true; } template struct segment_tree { // on monoid int n; vector a; function append; // associative T unit; template segment_tree(int a_n, T a_unit, F a_append) { n = pow(2,ceil(log2(a_n))); a.resize(2*n-1, a_unit); unit = a_unit; append = a_append; } void point_update(int i, T z) { a[i+n-1] = z; for (i = (i+n)/2; i > 0; i /= 2) { a[i-1] = append(a[2*i-1], a[2*i]); } } T range_concat(int l, int r) { return range_concat(0, 0, n, l, r); } T range_concat(int i, int il, int ir, int l, int r) { if (l <= il and ir <= r) { return a[i]; } else if (ir <= l or r <= il) { return unit; } else { return append( range_concat(2*i+1, il, (il+ir)/2, l, r), range_concat(2*i+2, (il+ir)/2, ir, l, r)); } } }; bool is_kadomatsu(int a, int b, int c) { if (a == b or b == c or c == a) return false; if (a < b and b < c) return false; if (a > b and b > c) return false; return true; } ll nc2_expected_value(int n, vector const & e) { segment_tree mint(n, n+1, [](int a, int b) { return min(a,b); }); segment_tree maxt(n, 0, [](int a, int b) { return max(a,b); }); repeat (i,n) { mint.point_update(i, e[i]); maxt.point_update(i, e[i]); } ll result = 0; repeat (i,n) { repeat_from (j,i+1,n) { int l, mn, mx, r; if (e[i] < e[j]) { l = maxt.range_concat(0,i); mn = mint.range_concat(i+1,j); mx = maxt.range_concat(i+1,j); r = mint.range_concat(j+1,n); } else { l = mint.range_concat(0,i); mn = mint.range_concat(i+1,j); mx = maxt.range_concat(i+1,j); r = maxt.range_concat(j+1,n); } int a = 0; if (i != 0 and is_kadomatsu(l, e[i], e[j])) setmax(a, l + e[i] + e[j]); if (i+1 != j and is_kadomatsu(e[i], mn, e[j])) setmax(a, mn + e[i] + e[j]); if (i+1 != j and is_kadomatsu(e[i], mx, e[j])) setmax(a, mx + e[i] + e[j]); if (j != n-1 and is_kadomatsu(e[i], e[j], r)) setmax(a, r + e[i] + e[j]); result += a; } } return result; } int main() { int n, m; cin >> n >> m; vector > e(m, vector(n)); repeat (y,m) repeat (x,n) cin >> e[y][x]; vector a(m); repeat (y,m) a[y] = nc2_expected_value(n, e[y]); cout << max_element(a.begin(), a.end()) - a.begin() << endl; return 0; }