#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; constexpr int INF = 1001001001; constexpr int mod = 1000000007; // constexpr int mod = 998244353; template inline bool chmax(T& x, T y){ if(x < y){ x = y; return true; } return false; } template inline bool chmin(T& x, T y){ if(x > y){ x = y; return true; } return false; } template struct Dinic{ const flow_t INF; struct Edge{ int to; flow_t cap; int rev; bool isrev; Edge(int to, flow_t cap, int rev, bool isrev) : to(to), cap(cap), rev(rev), isrev(isrev) {} }; vector> graph; vector min_cost; // sからの距離(bfsで調べる) vector iter; // どこまで調べ終わったか(dfs時に使用) Dinic(int V) : INF(numeric_limits::max() / 2){ graph.resize(V); } void add_edge(int from, int to, flow_t cap){ graph[from].push_back(Edge(to, cap, graph[to].size(), false)); graph[to].push_back(Edge(from, 0, graph[from].size() - 1, true)); } // 最短路探索 bool bfs(int s, int t){ min_cost.assign(graph.size(), -1); queue que; min_cost[s] = 0; que.push(s); while(!que.empty() && min_cost[t] == -1){ int p = que.front(); que.pop(); for(auto &e : graph[p]){ if(e.cap > 0 && min_cost[e.to] == -1){ min_cost[e.to] = min_cost[p] + 1; que.push(e.to); } } } return min_cost[t] != -1; } flow_t dfs(int v, int t, flow_t flow){ if(v == t) return flow; for(int &i = iter[v]; i < (int)graph[v].size(); ++i){ Edge &e = graph[v][i]; if(e.cap > 0 && min_cost[v] < min_cost[e.to]){ flow_t d = dfs(e.to, t, min(flow, e.cap)); if(d > 0){ e.cap -= d; graph[e.to][e.rev].cap += d; return d; } } } return 0; } flow_t max_flow(int s, int t){ flow_t flow = 0; // 最短路を求めて、そのパスに最大流を流す while(bfs(s, t)){ iter.assign(graph.size(), 0); flow_t f = 0; while((f = dfs(s, t, INF)) > 0) flow += f; } return flow; } }; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int H, W; cin >> H >> W; vector> G(H, vector(W)); int s = H * W + H + W, t = s + 1, V = s + 2; Dinic g(V); ll ans = 0; for(int i = 0; i < H; ++i){ for(int j = 0; j < W; ++j){ cin >> G[i][j]; int v = i * W + j; g.add_edge(s, v, 0); g.add_edge(v, t, G[i][j]); int w = H * W + i, x = H * W + H + j; g.add_edge(w, v, INF); g.add_edge(x, v, INF); } } vector R(H), C(W); for(int i = 0; i < H; ++i){ cin >> R[i]; ans += R[i]; int v = H * W + i; g.add_edge(s, v, R[i]); g.add_edge(v, t, 0); } for(int i = 0; i < W; ++i){ cin >> C[i]; ans += C[i]; int v = H * W + H + i; g.add_edge(s, v, C[i]); g.add_edge(v, t, 0); } ans -= g.max_flow(s, t); cout << ans << endl; return 0; }