建图:建立源点 s 和汇点 t,源点向仓库连边,容量为仓库库存,费用为 0,所有商店向汇点连边,容量为商店需求,费用为 0,所有仓库向商店连边,容量足够大,费用为从商店将货物移到该商店的单价,最后求解从 s 到 t 的费用流即为所求,为什么?不能发现,最后一定是满流的状态,从仓库流到商店的流量表示向该商店出多少货,费用即为单价乘以流的量,可行流和实际问题是一一对应的
设最大流为 f,k 为 spfa 算法常数,则:
时间复杂度:O(knmf)
代码
// Problem: 运输问题// Contest: AcWing// URL: https://www.acwing.com/problem/content/2194/// Memory Limit: 64 MB// Time Limit: 1000 ms// // Powered by CP Editor (https://cpeditor.org)// %%%Skyqwq#include<bits/stdc++.h>//#define int long long#define help {cin.tie(NULL); cout.tie(NULL);}#define pb push_back#define fi first#define se second#define mkp make_pairusingnamespace std;
typedeflonglong LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
template <typename T> boolchkMax(T &x, T y){ return (y > x) ? x = y, 1 : 0; }
template <typename T> boolchkMin(T &x, T y){ return (y < x) ? x = y, 1 : 0; }
template <typename T> voidinlineread(T &x){
int f = 1; x = 0; char s = getchar();
while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
x *= f;
}
constint N=155,M=(5005+N)*2,inf=1e9;
int m,n,S,T;
int h[N],e[M],ne[M],f[M],w[M],idx;
int d[N],incf[N],q[N],pre[N];
bool st[N];
voidadd(int a,int b,int c,int d){
e[idx]=b,f[idx]=c,w[idx]=d,ne[idx]=h[a],h[a]=idx++;
e[idx]=a,f[idx]=0,w[idx]=-d,ne[idx]=h[b],h[b]=idx++;
}
boolspfa(){
int hh=0,tt=1;
memset(d,0x3f,sizeof d);
memset(incf,0,sizeof incf);
q[0]=S,d[S]=0,incf[S]=inf;
while(hh!=tt)
{
int x=q[hh++];
if(hh==N)hh=0;
st[x]=false;
for(int i=h[x];~i;i=ne[i])
{
int y=e[i];
if(d[y]>d[x]+w[i]&&f[i])
{
d[y]=d[x]+w[i];
pre[y]=i;
incf[y]=min(incf[x],f[i]);
if(!st[y])
{
q[tt++]=y;
if(tt==N)tt=0;
st[y]=true;
}
}
}
}
return incf[T]>0;
}
intEK(){
int cost=0;
while(spfa())
{
int t=incf[T];
cost+=t*d[T];
for(int i=T;i!=S;i=e[pre[i]^1])
f[pre[i]]-=t,f[pre[i]^1]+=t;
}
return cost;
}
intmain(){
memset(h,-1,sizeof h);
scanf("%d%d",&m,&n);
S=0,T=m+n+1;
int a,b,c;
for(int i=1;i<=m;i++)
{
scanf("%d",&a);
add(S,i,a,0);
}
for(int i=1;i<=n;i++)
{
scanf("%d",&b);
add(i+m,T,b,0);
}
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
{
scanf("%d",&c);
add(i,j+m,inf,c);
}
printf("%d\n",EK());
for(int i=0;i<idx;i+=2)
{
f[i]+=f[i^1],f[i^1]=0;
swap(w[i],w[i^1]);
}
printf("%d",-EK());
return0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!