#include #include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; const ll INF = 1e15; struct edge {ll to, cap, rev;}; class FordFolkerson{ public: FordFolkerson(ll n){ N = n; G = vector>(n, vector()); used = vector(n, false); } void add_edge(ll from, ll to, ll cap){ G[from].push_back((edge{to, cap, (ll)G[to].size()})); G[to].push_back((edge{from, 0, (ll)G[from].size()-1})); } ll max_flow(ll s, ll t){ ll flow = 0; while(true){ clear_used(); ll f = dfs(s, t, INF); if(f == 0){ break; } flow += f; } return flow; } private: vector> G; vector used; ll N; void clear_used(){ for(ll i = 0; i < N; i++) used[i] = false; } ll dfs(ll v, ll t, ll f){ if(v == t) return f; used[v] = true; for(ll i = 0; i < G[v].size(); i++){ edge &e = G[v][i]; if(!used[e.to] && e.cap > 0){ ll d = dfs(e.to, t, min(f, e.cap)); if(d > 0){ e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } }; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int h, w; cin >> h >> w; vector> g(h, vector(w)); for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ cin >> g[i][j]; } } vector r(h), c(w); for(int i = 0; i < h; i++) cin >> r[i]; for(int i = 0; i < w; i++) cin >> c[i]; // FordFolkerson mf(2+h+w+h*w); atcoder::mf_graph mf(2+h+w+h*w); int s = 0, t = 1+h+w+h*w; auto row_index = [&](int i){ return i+1; }; auto col_index = [&](int j){ return h+j; }; auto cell_index = [&](int i, int j){ return h+w+w*i+j; }; for(int i = 0; i < h; i++) mf.add_edge(s, row_index(i), r[i]); for(int j = 0; j < w; j++) mf.add_edge(s, col_index(j), c[j]); for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ mf.add_edge(row_index(i), cell_index(i, j), INF); mf.add_edge(col_index(j), cell_index(i, j), INF); mf.add_edge(cell_index(i, j), t, g[i][j]); } } cout << accumulate(r.begin(), r.end(), 0ll)+accumulate(c.begin(), c.end(), 0ll)-mf.flow(s, t) << endl; }