http://acm.hdu.edu.cn/showproblem.php?pid=1569
与Hdoj1565类似,但 这里是n*m的矩阵,而且n、m<=50,用邻接矩阵存会超内存,所以改为邻接表,但算法思想是一样滴。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
int map[55][55];
int a[2600],pre[2600],flow[2600][2600];
int m,n,sum;
int s,t;
int maxflow;
struct node
{
int v,w;
};
vector <struct node> edge[2600];
void build_graph()
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
int it = (i-1)*m+j;
if((i+j)%2 == 0)
edge[s].push_back((struct node){it,map[i][j]});
else
edge[it].push_back((struct node){t,map[i][j]});
}
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
if((i+j)%2==0)
{
int it = (i-1)*m+j;
if(j < m)
{
edge[it].push_back((struct node){it+1,INF});
edge[it+1].push_back((struct node){it,0});
}
if(j > 1)
{
edge[it].push_back((struct node){it-1,INF});
edge[it-1].push_back((struct node){it,0});
}
if(i > 1)
{
edge[it].push_back((struct node){it-m,INF});
edge[it-m].push_back((struct node){it,0});
}
if(i < n)
{
edge[it].push_back((struct node){it+m,INF});
edge[it+m].push_back((struct node){it,0});
}
}
}
}
}
void E_K()
{
queue<int>que;
while(!que.empty())
que.pop();
memset(flow,0,sizeof(flow));
while(true)
{
memset(a,0,sizeof(a));
a[s] = INF;
que.push(s);
while(!que.empty())
{
int u = que.front();
que.pop();
for(int i = 0; i < (int)edge[u].size(); i++)
{
int v = edge[u][i].v;
int w = edge[u][i].w;
if(!a[v] && flow[u][v] < w)
{
a[v] = min(a[u],w-flow[u][v]);
que.push(v);
pre[v] = u;
}
}
}
if(a[t] == 0)
break;
for(int u = t; u!=s; u = pre[u])
{
flow[pre[u]][u] += a[t];
flow[u][pre[u]] -= a[t];
}
maxflow += a[t];
}
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
sum = 0;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
scanf("%d",&map[i][j]);
sum += map[i][j];
}
}
s = 0;
t = n*m+1;
for(int i = 0; i <= t; i++)
edge[i].clear();
build_graph();
maxflow = 0;
E_K();
printf("%d\n",sum-maxflow);
}
return 0;
}