标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5425 Accepted Submission(s): 1695
#include <bits/stdc++.h> using namespace std; #define maxn 55 const int inf = 0x3f3f3f3f; int M, N; int mp[maxn][maxn]; int mark[maxn][maxn]; int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; struct Edge { int from, to, cap, flow; Edge(int f, int t, int c, int fl) { from = f; to = t; cap = c; flow = fl; } }; vector <Edge> edges; vector <int> G[maxn*maxn]; int s, t, n, m; int cur[maxn*maxn], vis[maxn*maxn], d[maxn*maxn]; void AddEdge(int from, int to, int cap) { edges.push_back(Edge(from, to, cap, 0)); edges.push_back(Edge(to, from, 0, 0)); m = edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool bfs() { memset(vis, 0, sizeof(vis)); d[s] = 0; vis[s] = 1; queue <int> q; q.push(s); while(!q.empty()) { int u = q.front(); q.pop(); for(int i = 0; i < G[u].size(); i++) { Edge &e = edges[G[u][i]]; if(!vis[e.to] && e.cap > e.flow) { vis[e.to] = 1; d[e.to] = d[u]+1; q.push(e.to); } } } return vis[t]; } int dfs(int x, int a) { if(x == t || a == 0) return a; int flow = 0, f; for(int &i = cur[x]; i < G[x].size(); i++) { Edge &e = edges[G[x][i]]; if(d[x]+1 == d[e.to] && (f = dfs(e.to, min(a, e.cap-e.flow))) > 0) { e.flow += f; edges[G[x][i]^1].flow -= f; flow += f; a -= f; if(a == 0) break; } } return flow; } int Maxflow() { int flow = 0; while(bfs()) { memset(cur, 0, sizeof(cur)); flow += dfs(s, inf); } return flow; } bool judge(int x, int y) { if(x >= 1 && x <= N && y >= 1 && y <= M) return true; return false; } int main() { while(~scanf("%d%d", &N, &M)) { edges.clear(); for(int i = 0; i < maxn*maxn; i++) G[i].clear(); int sum = 0; for(int i = 1; i <= N; i++) { for(int j = 1; j <= M; j++) { scanf("%d", &mp[i][j]); sum += mp[i][j]; } } s = 0; t = N*M+1; for(int i = 1; i <= N; i++) { for(int j = 1; j <= M; j++) { if((i+j)%2 == 0) { AddEdge(s, (i-1)*M+j, mp[i][j]); if(i > 1) AddEdge((i-1)*M+j, (i-2)*M+j, inf); if(j > 1) AddEdge((i-1)*M+j, (i-1)*M+j-1, inf); if(i < N) AddEdge((i-1)*M+j, i*M+j, inf); if(j < M) AddEdge((i-1)*M+j, (i-1)*M+j+1, inf); } else AddEdge((i-1)*M+j, t, mp[i][j]); } } printf("%d\n", sum - Maxflow()); } }
标签:
原文地址:http://www.cnblogs.com/titicia/p/4695226.html