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
80
81
82
83
84
85
86
87
88
89
90
91
92
#ifdef LOC
#include "debuglib.hpp"
#else
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#define deb(...)
#define DBP(...)
#endif
using namespace std;
using   ll         = long long;
using   vi         = vector<int>;
using   pii        = pair<int, int>;
#define pb           push_back
#define mp           make_pair
#define x            first
#define y            second
#define rep(i, b, e) for (int i = (b); i < (e); i++)
#define each(a, x)   for (auto& a : (x))
#define all(x)       (x).begin(), (x).end()
#define sz(x)        int((x).size())

int n, m, k;
vector<pair<ll, vector<ll>>> ascending;
vector<vector<ll>> descending;

vector<ll> solveAscending() {
	vector<ll> ans(n*m+1);
	sort(all(ascending), [&](const auto& l, const auto& r) { return l.x > r.x; });

	vector<ll> tmp(m, INT64_MAX);
	ll sum = 0;
	int count = 0;

	for (auto& [s, tower] : ascending) {
		sum += s;
		count += m;
		ll acc = s;
		rep(i, 0, m) {
			tmp[i] = min(tmp[i], acc);
			ans[count-m+i] = sum - tmp[i];
			acc -= tower[i];
		}
		ans[count] = sum;
	}

	reverse(all(ascending));
	tmp.assign(m, 0);

	for (auto& [s, tower] : ascending) {
		sum -= s;
		count -= m;
		ll acc = 0;
		rep(i, 0, m) {
			tmp[i] = max(tmp[i], acc);
			ans[count+i] = max(ans[count+i], sum + tmp[i]);
			acc += tower[i];
		}
	}

	return ans;
}

vector<ll> solveDescending() {
	vector<ll> merged, ans(n*m+1);
	each(vec, descending) merged.insert(merged.end(), all(vec));
	sort(all(merged), greater<ll>());
	rep(i, 0, sz(merged)) ans[i+1] = ans[i] + merged[i];
	return ans;
}

int main() {
	cin.sync_with_stdio(0); cin.tie(0);
	cin >> n >> m >> k;

	rep(i, 0, n) {
		vector<ll> tower(m);
		each(a, tower) cin >> a;
		if (is_sorted(all(tower))) {
			ll sum = accumulate(all(tower), 0LL);
			ascending.pb({ sum, move(tower) });
		} else {
			descending.pb(move(tower));
		}
	}

	auto bestAsc = solveAscending();
	auto bestDesc = solveDescending();

	ll ans = 0;
	rep(i, 0, k+1) ans = max(ans, bestAsc[i] + bestDesc[k-i]);
	cout << ans << '\n';
}