【网络流24题】运输问题(费用流)
题面
题解
大水题。。。
源点向仓库连,容量为货物量,费用为0
仓库向商店连,容量INF,费用题目给出来了
商店向汇点连,容量为需求量,费用为0
简直裸的费用流
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MAX 5000
#define MAXL 500000
#define INF 1000000000
inline int read()
{
int x=0,t=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
struct Line
{
int v,next,w,fy;
}e[MAXL];
bool vis[MAX];
int h[MAX],cnt=2;
int a[MAX],b[MAX],c[MAX][MAX];
inline void Add(int u,int v,int w,int fy)
{
e[cnt]=(Line){v,h[u],w,fy};h[u]=cnt++;
e[cnt]=(Line){u,h[v],0,-fy};h[v]=cnt++;
}
int pe[MAX],pr[MAX],dis[MAX];
int S,T,Cost,n,m,Flow,opt=1;
bool SPFA()
{
memset(dis,63,sizeof(dis));
queue<int> Q;
Q.push(S);dis[S]=0;
while(!Q.empty())
{
int u=Q.front();Q.pop();
for(int i=h[u];i;i=e[i].next)
{
int v=e[i].v;
if(e[i].w&&dis[v]>dis[u]+e[i].fy)
{
dis[v]=dis[u]+e[i].fy;
pe[v]=i;pr[v]=u;
if(!vis[v])vis[v]=true,Q.push(v);
}
}
vis[u]=false;
}
if(dis[T]>=INF)return false;
int flow=INF;
for(int i=T;i!=S;i=pr[i])flow=min(flow,e[pe[i]].w);
for(int i=T;i!=S;i=pr[i])e[pe[i]].w-=flow,e[pe[i]^1].w+=flow;
Cost+=opt*flow*dis[T];
Flow+=flow;
return true;
}
int main()
{
freopen("tran.in","r",stdin);
freopen("tran.out","w",stdout);
m=read();n=read();
for(int i=1;i<=m;++i)a[i]=read();
for(int j=1;j<=n;++j)b[j]=read();
for(int i=1;i<=m;++i)
for(int j=1;j<=n;++j)
c[i][j]=read();
S=0;T=n+m+1;
memset(h,0,sizeof(h));cnt=2;
for(int i=1;i<=m;++i)Add(S,i,a[i],0);
for(int j=1;j<=n;++j)Add(j+m,T,b[j],0);
for(int i=1;i<=m;++i)
for(int j=1;j<=n;++j)
Add(i,j+m,INF,c[i][j]);
Cost=Flow=0;opt=1;
while(SPFA());
printf("%d\n",Cost);
memset(h,0,sizeof(h));cnt=2;
for(int i=1;i<=m;++i)Add(S,i,a[i],0);
for(int j=1;j<=n;++j)Add(j+m,T,b[j],0);
for(int i=1;i<=m;++i)
for(int j=1;j<=n;++j)
Add(i,j+m,INF,-c[i][j]);
Cost=Flow=0;opt=-1;
while(SPFA());
printf("%d\n",Cost);
return 0;
}