题目:
题解:
将棋盘进行黑白染色,黑色和黑色可以一起涂。建立源点和汇点,源点连黑点容量为黑点值,汇点连白点容量为白点值,其他如果黑白点相邻,则连容量为INF的边
其实就是求最小割(最大流),只要源点和汇点不再相连,黑格和白格就不会相连
对于这道题,割掉了就不选了嘛
代码:
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#define INF 1e9
using namespace std;
const int N=905;
int id[35][35];
int tot=-1,nxt[N*4],point[N],v[N*4],remind[N*4],dis[N],cur[N],a[35][35];
void addline(int x,int y,int cap)
{
++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; remind[tot]=cap;
++tot; nxt[tot]=point[y]; point[y]=tot; v[tot]=x; remind[tot]=0;
}
int dfs(int now,int t,int limit)
{
if (now==t || !limit) return limit;
int flow=0,f;
for (int i=cur[now];i!=-1;i=nxt[i])
{
cur[now]=i;
if (dis[v[i]]==dis[now]+1 && (f=dfs(v[i],t,min(remind[i],limit))))
{
flow+=f;
limit-=f;
remind[i]-=f;
remind[i^1]+=f;
if (!limit) break;
}
}
return flow;
}
bool bfs(int s,int t)
{
queue<int>q;
q.push(s);
memset(dis,0x7f,sizeof(dis));
dis[s]=0;
for (int i=s;i<=t;i++) cur[i]=point[i];
while (!q.empty())
{
int x=q.front(); q.pop();
for (int i=point[x];i!=-1;i=nxt[i])
if (dis[v[i]]>INF && remind[i])
{q.push(v[i]); dis[v[i]]=dis[x]+1;}
}
return dis[t]<INF;
}
int dinic(int s,int t)
{
int ans=0;
while (bfs(s,t)) ans+=dfs(s,t,INF);
return ans;
}
int main()
{
int bl=0,wh=0,sum=0,n,m;
memset(nxt,-1,sizeof(nxt));
memset(point,-1,sizeof(point));
scanf("%d%d",&m,&n);
for (int i=1;i<=m;i++)
for (int j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
sum+=a[i][j];
if ((i+j)%2)//白点
id[i][j]=++wh;
else id[i][j]=++bl;
}
for (int i=1;i<=m;i++)
for (int j=1;j<=n;j++)
if ((i+j)%2) addline(id[i][j]+bl,wh+bl+1,a[i][j]);
else
{
addline(0,id[i][j],a[i][j]);
if (i+1<=m) addline(id[i][j],id[i+1][j]+bl,INF);
if (j+1<=n) addline(id[i][j],id[i][j+1]+bl,INF);
if (i-1>=1) addline(id[i][j],id[i-1][j]+bl,INF);
if (j-1>=1) addline(id[i][j],id[i][j-1]+bl,INF);
}
printf("%d",sum-dinic(0,m*n+1));
}