hzwer的题解太难想了,于是还是写个容易想的吧。
最小割
与S联通表示选0(文),与T联通表示选1(理)
源点S向每个同学x连一条容量为aij的边
每个同学x向汇点T连一条容量为bij的边
对于同时为1的收益,向汇点T连一条容量为价值的边
对应的点x向收益连一条容量为inf的边
对于同时为0的收益,源点S向连一条容量为价值的边
收益向对应的点x连一条容量为inf的边
点数 5nm 50000
边数 (3*4nm+2nm)*2=28nm 300000
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<iostream>
#define inf 1000000000
#define maxn 50010
#define maxm 300010
using namespace std;
int head[maxn],to[maxm],c[maxm],next[maxm],q[maxn],d[maxn];
int num,n,m,s,t,ans,tot;
void addedge(int x,int y,int z)
{
num++;to[num]=y;c[num]=z;next[num]=head[x];head[x]=num;
num++;to[num]=x;c[num]=0;next[num]=head[y];head[y]=num;
}
bool bfs()
{
memset(d,-1,sizeof(d));
int l=0,r=1;
q[1]=s;d[s]=0;
while (l<r)
{
int x=q[++l];
for (int p=head[x];p;p=next[p])
if (c[p] && d[to[p]]==-1)
{
d[to[p]]=d[x]+1;
q[++r]=to[p];
}
}
if (d[t]==-1) return 0; else return 1;
}
int find(int x,int low)
{
if (x==t || low==0) return low;
int totflow=0;
for (int p=head[x];p;p=next[p])
if (c[p] && d[to[p]]==d[x]+1)
{
int a=find(to[p],min(low,c[p]));
c[p]-=a;c[p^1]+=a;
low-=a;totflow+=a;
if (low==0) return totflow;
}
if (low) d[x]=-1;
return totflow;
}
int cal(int x,int y)
{
return (x-1)*n+y;
}
int main()
{
scanf("%d%d",&n,&m);
num=1;s=0;t=5*n*m;tot=n*m;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
int x;
scanf("%d",&x);
addedge(s,cal(i,j),x);ans+=x;
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
int x;
scanf("%d",&x);
addedge(cal(i,j),t,x);ans+=x;
}
for (int i=1;i<n;i++)
for (int j=1;j<=m;j++)
{
int x;
scanf("%d",&x);
tot++;addedge(s,tot,x);
addedge(tot,cal(i,j),inf);addedge(tot,cal(i+1,j),inf);
ans+=x;
}
for (int i=1;i<n;i++)
for (int j=1;j<=m;j++)
{
int x;
scanf("%d",&x);
tot++;addedge(tot,t,x);
addedge(cal(i,j),tot,inf);addedge(cal(i+1,j),tot,inf);
ans+=x;
}
for (int i=1;i<=n;i++)
for (int j=1;j<m;j++)
{
int x;
scanf("%d",&x);
tot++;addedge(s,tot,x);
addedge(tot,cal(i,j),inf);addedge(tot,cal(i,j+1),inf);
ans+=x;
}
for (int i=1;i<=n;i++)
for (int j=1;j<m;j++)
{
int x;
scanf("%d",&x);
tot++;addedge(tot,t,x);
addedge(cal(i,j),tot,inf);addedge(cal(i,j+1),tot,inf);
ans+=x;
}
while (bfs()) ans-=find(s,inf);
printf("%d\n",ans);
return 0;
}