#include using namespace std; // https://kopricky.github.io/code/NetworkFlow/dinic.html template class Dinic { private: static_assert(std::is_integral::value, "Integral required."); struct edge{ int to; T cap; int rev; }; const int V; vector level, iter, que; static unsigned long long floor2(unsigned long long v){ v = v | (v >> 1), v = v | (v >> 2); v = v | (v >> 4), v = v | (v >> 8); v = v | (v >> 16), v = v | (v >> 32); return v - (v >> 1); } void bfs(const int s, const T base) { fill(level.begin(), level.end(), -1); level[s] = 0; int qh = 0, qt = 0; for(que[qt++] = s; qh < qt;){ int v = que[qh++]; for(edge& e : G[v]){ if(level[e.to] < 0 && e.cap >= base){ level[e.to] = level[v] + 1; que[qt++] = e.to; } } } } T dfs(const int v, const int t, const T base, const T f) { if(v == t) return f; T sum = 0; for(int& i = iter[v]; i < (int)G[v].size(); i++){ edge& e = G[v][i]; if(e.cap >= base && level[v] < level[e.to]){ T d = dfs(e.to, t, base, min(f - sum, e.cap)); if(d > 0){ e.cap -= d; G[e.to][e.rev].cap += d; sum += d; if(f - sum < base) break; } } } return sum; } public: vector > G; Dinic(const int node_size) : V(node_size), level(V), iter(V), que(V), G(V){} //辺を張る void add_edge(const int from, const int to, const T cap) { G[from].push_back((edge){to, cap, (int)G[to].size()}); G[to].push_back((edge){from, (T)0, (int)G[from].size()-1}); } //最大流を計算(max_cap は辺の容量の上限) T solve(const int s, const int t, const T max_cap){ T flow = 0; for(T base = floor2(max_cap); base >= 1;){ bfs(s, base); if(level[t] < 0){ base >>= 1; continue; } fill(iter.begin(), iter.end(), 0); flow += dfs(s, t, base, numeric_limits::max()); } return flow; } }; constexpr long long inf = 1e18; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int h, w; cin >> h >> w; vector< vector > g(h, vector(w)); for (auto&& v : g) { for (auto&& e : v) { cin >> e; } } vector r(h); for (auto&& e : r) { cin >> e; } vector c(w); for (auto&& e : c) { cin >> e; } int s = h + w + h * w, t = s + 1; Dinic d(t + 1); long long res = 0; for (int i = 0; i < h; ++i) { long long sg = 0; for (int j = 0; j < w; ++j) { sg += g[i][j]; } res += r[i]; d.add_edge(s, i, r[i]); d.add_edge(i, t, sg); } for (int j = 0; j < w; ++j) { long long sg = 0; for (int i = 0; i < h; ++i) { sg += g[i][j]; } res += c[j]; d.add_edge(s, h + j, c[j]); d.add_edge(h + j, t, sg); } for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { int v = h + w + i * w + j; res += g[i][j]; d.add_edge(s, v, g[i][j]); d.add_edge(v, i, inf); d.add_edge(v, h + j, inf); } } res -= d.solve(s, t, inf); cout << res << '\n'; }