- 题意(原题):
- 给出一个网格(有斜向边),左上角为源点,右下角为汇点,每条边有流量,请问截留所有流量的代价为多少(截留一条边的代价与该边实际使用最大流量相等(应该没理解错))。
- 思路:
- 最大流:每条边每单位时间允许经过一定流量,源点流量无限,则为每单位时间汇点所能接受的最大流量。
- 最小割定理:把一个图源点汇点分开,代价等于该图最大流。
- 因此我们使用网络流解决这一问题。我使用的是dinic模版(貌似有些过时?)
- 代码:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define MAXN 1000001
using namespace std;
struct node
{
int x,y,c,next,other;
}a[MAXN*6];int len=0,n,m,st,ed,last[MAXN],list[MAXN],h[MAXN];
int getp(int x,int y)
{
return (x-1)*m+y;
}
void ins(int x,int y,int c)
{
len++;
a[len].x=x;a[len].y=y;a[len].c=c;
a[len].next=last[x];last[x]=len;a[len].other=len+1;
len++;
a[len].x=y;a[len].y=x;a[len].c=c;
a[len].next=last[y];last[y]=len;a[len].other=len-1;
}
bool bfs()
{
int head=1,tail=1;list[1]=st;
memset(h,0,sizeof(h));h[st]=1;
while(head<=tail)
{
int x=list[head];
for(int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if(!h[y]&&a[k].c)
{
h[y]=h[x]+1;
list[++tail]=y;
}
}
head++;
}
return h[ed]?true:false;
}
int dfs(int x,int flow)
{
if(x==ed)return flow;
int cnt=0;
for(int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if(a[k].c&&h[x]+1==h[y]&&flow>cnt)
{
int z=dfs(y,min(a[k].c,flow-cnt));
cnt+=z;a[k].c-=z;a[a[k].other].c+=z;
}
}
if(!cnt)h[x]=0;
return cnt;
}
int main()
{
scanf("%d%d",&n,&m);st=getp(1,1);ed=getp(n,m);
int x;
for(int i=1;i<=n;i++)
for(int j=1;j<m;j++)
{
scanf("%d",&x);
ins(getp(i,j),getp(i,j+1),x);
}
for(int i=1;i<n;i++)
for(int j=1;j<=m;j++)
{
scanf("%d",&x);
ins(getp(i,j),getp(i+1,j),x);
}
for(int i=1;i<n;i++)
for(int j=1;j<m;j++)
{
scanf("%d",&x);
ins(getp(i,j),getp(i+1,j+1),x);
}
int ans=0;
while(bfs())
{
int x=1;
while(x)
{
x=dfs(st,999999999);
ans+=x;
}
}
printf("%d\n",ans);
return 0;
}