1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m, k;
    cin >> n >> m >> k;
    vector<vector<int64_t>> inc, dec;
    for (int i = 0; i < n; ++i) {
        vector<int64_t> row(m);
        for (auto& a : row) {
            cin >> a;
        }
        if (ranges::is_sorted(row)) {
            inc.push_back(row);
        }
        else {
            dec.push_back(row);
        }
    }

    vector pref(inc.size(), vector<int64_t> (m + 1));
    for (int i = 0; i < (int)inc.size(); ++i) {
        for (int j = 0; j < m; ++j) {
            pref[i][j + 1] = pref[i][j] + inc[i][j];
        }
    }
    ranges::sort(pref, [](auto& lhs, auto& rhs) { return lhs.back() > rhs.back(); });
    vector<int64_t> pref_pref(inc.size() + 1);
    for (int i = 0; i < (int)inc.size(); ++i) {
        pref_pref[i + 1] = pref_pref[i] + pref[i][m];
    }
    vector max_down(inc.size() + 1, vector<int64_t> (m + 1));
    for (int i = (int)inc.size() - 1; i >= 0; --i) {
        for (int j = 0; j <= m; ++j) {
            max_down[i][j] = max(max_down[i + 1][j], pref[i][j]);
        }
    }
    vector max_up(inc.size() + 1, vector<int64_t> (m + 1, -1e18));
    for (int i = 0; i < (int)inc.size(); ++i) {
        for (int j = 0; j <= m; ++j) {
            max_up[i + 1][j] = max(max_up[i][j], pref[i][j] - pref[i][m]);
        }
    }
    
    vector<int64_t> res_inc(m * inc.size() + 1), res_dec(m * dec.size() + 1);
    for (int cnt_inc = 1; cnt_inc < (int)res_inc.size() - 1; ++cnt_inc) {
        int full = cnt_inc / m;
        res_inc[cnt_inc] = max(
            max_down[full][cnt_inc % m] + pref_pref[full],
            max_up[full + 1][cnt_inc % m] + pref_pref[full + 1]
        );
    }
    res_inc[m * inc.size()] = pref_pref[inc.size()];

    priority_queue<tuple<int64_t, int, int>> Q;
    for (int i = 0; i < (int)dec.size(); ++i) {
        Q.emplace(dec[i][0], i, 1);
    }
    for (int cnt_dec = 1; cnt_dec < (int)res_dec.size(); ++cnt_dec) {
        auto [a, i, j] = Q.top();
        Q.pop();
        res_dec[cnt_dec] = res_dec[cnt_dec - 1] + a;
        if (j < m) {
            Q.emplace(dec[i][j], i, j + 1);
        }
    }

    int64_t ans = 0;
    for (int cnt_inc = 0; cnt_inc < (int)res_inc.size(); ++cnt_inc) {
        if (0 <= k - cnt_inc && k - cnt_inc < (int)res_dec.size()) {
            ans = max(ans, res_inc[cnt_inc] + res_dec[k - cnt_inc]);
        }
    }
    cout << ans << '\n';
    return 0;
}