您的位置:首页 > 理论基础 > 计算机网络

【网络流24题】方格取数问题

2017-01-04 07:07 302 查看
(网络流24题大多需要spj,所以需要一个有spj的oj,本系列代码均在www.oj.swust.edu.cn测试通过)

这道题我认为精髓就是将整个棋盘染色,使得相邻的两个格子染色不同,相信说到这里大家都知道怎么染了,就像很多地砖的染色一样,使得染色相间分布,这样一个棋盘就变成了一个二分图,一个格子和相邻的四个格子链接一条INF,每个格子向两边链接一条数字大小的边,跑一边最小割就行了。

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
#include<algorithm>
using namespace std;
#define INF 100000000
struct bian
{
int l,r,f;
}a[1000000];
int fir[1000000];
int nex[1000000];
int d[100000];
int s=0,t=99999;
bool bfs()
{
static int dui[1000000];
memset(d,-1,sizeof(d));
int top=1,my_final=2;
dui[1]=s;
d[s]=1;
while(top<my_final)
{
int u=dui[top++];
for(int o=fir[u];o;o=nex[o])
{
if(d[a[o].r]==-1 && a[o].f)
{
d[a[o].r]=d[u]+1;
dui[my_final++]=a[o].r;
if(a[o].r==t) return true;
}
}
}
return false;
}
int dinic(int u,int flow)
{
if(u==t) return flow;
int left=flow;
for(int o=fir[u];o&&left;o=nex[o])
{
if(a[o].f && d[a[o].r]==d[u]+1)
{
int temp=dinic(a[o].r,min(left,a[o].f));
if(!temp) d[a[o].r]=-1;
left-=temp;
a[o].f-=temp;
a[o^1].f+=temp;
}
}
return flow-left;
}
int tot=1;
void add_edge(int l,int r,int f)
{
a[++tot].l=l;
a[tot].r=r;
a[tot].f=f;
nex[tot]=fir[l];
fir[l]=tot;
}
int v[50][50];
int xx[4]={-1,1,0,0};
int yy[4]={0,0,1,-1};
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d",&v[i][j]);
ans+=v[i][j];
int wz=i*m-m+j;
if(!((i+j)&1))
{
add_edge(s,wz,v[i][j]);
add_edge(wz,s,0);
for(int k=0;k<=3;k++)
{
int x=i+xx[k];
int y=j+yy[k];
int nwz=x*m-m+y;
if(nwz>0 && x>0 && y>0 && x<=n && y<=m)
{
add_edge(wz,nwz,INF);
add_edge(nwz,wz,0);
}
}
}
else
{
add_edge(wz,t,v[i][j]);
add_edge(t,wz,0);
}
}
}
while(bfs()) ans-=dinic(s,INF);
cout<<ans;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: