# 洛谷P2774方格取数（网络流24题）

xiaoxiao2021-02-28  28

#include<cstdio> #include<iostream> #include<algorithm> #include<vector> #include<queue> #include<cstring> using namespace std; struct edge { int to, cap, rev; }; vector<edge>G[10010]; int level[10011], iter[10011]; int n, m; void addedge(int from, int to, int cap) { edge e; e.to = to; e.cap = cap; e.rev = G[to].size(); G[from].push_back(e); e.to = from; e.cap = 0; e.rev = G[from].size() - 1;//一定要小心反向边的cap为0！！！ G[to].push_back(e); } void bfs(int s) { memset(level, -1, sizeof(level));//每次bfs的时候构图都不同，要memset queue<int>que; level[s] = 0; que.push(s); while (!que.empty()) { int t = que.front(); que.pop(); for (int i = 0; i < G[t].size(); i++) { edge e = G[t][i]; if (e.cap&&level[e.to] < 0) { level[e.to] = level[t] + 1; que.push(e.to); } } } } int dfs(int v, int t, int f) { if (v == t) return f; for (int &i = iter[v]; i < G[v].size(); i++) {//因为每次dfs的时候如果找到解就return了，所以有必要记录上次这个点搜到哪了 edge &e = G[v][i]; if (e.cap&&level[e.to] > level[v]) { int d = dfs(e.to, t, min(f, e.cap)); if (d) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } int maxflow(int s, int t) { int flow = 0; for (;;) { bfs(s); if (level[t] < 0)//说明此时已经不存在没有搜过的路了 return flow; memset(iter, 0, sizeof(iter)); int f; while (f = dfs(s, t, 1 << 30))//要搜完当期状况下的所有可能 flow += f; } } int main() { int i, j, num[101][101], total = 0; cin >> m >> n; for(i=1;i<=m;i++) for (j = 1; j <= n; j++) { scanf("%d", &num[i][j]); total += num[i][j]; } int move[4][2] = { 0,-1,-1,0,0,1,1,0 }; for(i=1;i<=m;i++) for (j = 1; j <= n; j++) { if (i % 2 == j % 2) { addedge(0, (i - 1)*n + j, num[i][j]); for (int k = 0; k < 4; k++) { if (i + move[k][0] > 0 && i + move[k][0] <= m && j + move[k][1] > 0 && j + move[k][1] <= n) addedge((i - 1)*n + j, (i + move[k][0] - 1)*n + j + move[k][1], 1 << 30); } } else { addedge((i - 1)*n + j, 10005, num[i][j]); } } int ans =total- maxflow(0, 10005); cout << ans << endl; return 0; }