版权声明:https://blog.csdn.net/huashuimu2003 https://blog.csdn.net/huashuimu2003/article/details/91352398
title
LUOGU 4015
题目描述
W 公司有 m 个仓库和 n 个零售商店。第 i 个仓库有 个单位的货物;第 j 个零售商店需要 个单位的货物。
货物供需平衡,即
从第 i 个仓库运送每单位货物到第 j 个零售商店的费用为 。
试设计一个将仓库中所有货物运送到零售商店的运输方案,使总运输费用最少。
输入输出格式
输入格式:
第 1 行有 2 个正整数 m 和 n,分别表示仓库数和零售商店数。
接下来的一行中有 m 个正整数 ,表示第 i 个仓库有 个单位的货物。
再接下来的一行中有 n 个正整数 ,表示第 j 个零售商店需要 个单位的货物。
接下来的 m 行,每行有 n 个整数,表示从第 i 个仓库运送每单位货物到第 j 个零售商店的费用 。
输出格式:
两行分别输出最小运输费用和最大运输费用。
输入输出样例
输入样例#1:
2 3
220 280
170 120 210
77 39 105
150 186 122
输出样例#1:
48500
69140
说明
analysis
很经典的模型。
建图:
- 1. 向 连接容量为 ,费用为 的边。
- 2. 向 连接容量为 ,费用为 。
- 3. 向 连接容量为 ,费用为 的边。
跑一个最小费用最大流,轻松完成第一个任务。
第二个任务只要清空图,然后重新连接为费用是
的边即可。
很轻松吧才怪。
code
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10,maxm=210,inf=0x3f3f3f3f;
char buf[1<<15],*fs,*ft;
inline char getc() { return (ft==fs&&(ft=(fs=buf)+fread(buf,1,1<<15,stdin),ft==fs))?0:*fs++; }
template<typename T>inline void read(T &x)
{
x=0;
T f=1, ch=getchar();
while (!isdigit(ch) && ch^'-') ch=getchar();
if (ch=='-') f=-1, ch=getchar();
while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
x*=f;
}
template<typename T>inline void write(T x)
{
if (!x) { putchar('0'); return ; }
if (x<0) putchar('-'), x=-x;
T num=0, ch[20];
while (x) ch[++num]=x%10+48, x/=10;
while (num) putchar(ch[num--]);
}
int ver[maxn<<1],edge[maxn<<1],Next[maxn<<1],cost[maxn<<1],head[maxn],len=1;
inline void add(int x,int y,int z,int c)
{
ver[++len]=y,edge[len]=z,cost[len]=c,Next[len]=head[x],head[x]=len;
ver[++len]=x,edge[len]=0,cost[len]=-c,Next[len]=head[y],head[y]=len;
}
int s,t;
int dist[maxn],incf[maxn],pre[maxn];
bool vis[maxn];
inline bool spfa()
{
memset(dist,0x3f,sizeof(dist));
memset(vis,0,sizeof(vis));
queue<int>q;q.push(s);
dist[s]=0,vis[s]=1,incf[s]=1<<30;
while (!q.empty())
{
int x=q.front();
q.pop();
vis[x]=0;
for (int i=head[x]; i; i=Next[i])
{
if (!edge[i]) continue;
int y=ver[i];
if (dist[y]>dist[x]+cost[i])
{
dist[y]=dist[x]+cost[i];
incf[y]=min(incf[x],edge[i]);
pre[y]=i;
if (!vis[y]) q.push(y),vis[y]=1;
}
}
}
if (dist[t]==inf) return false;
else return true;
}
long long maxflow,ans;
inline void update()
{
int x=t;
while (x!=s)
{
int i=pre[x];
edge[i]-=incf[t];
edge[i^1]+=incf[t];
x=ver[i^1];
}
maxflow+=incf[t];
ans+=dist[t]*incf[t];
}
int m,n,a[maxm],b[maxm],c[maxm][maxm];
inline void build(int off)
{
memset(head,0,sizeof(head));
len=1;
ans=maxflow=0;
s=0,t=m+n+1;
for (int i=1; i<=m; ++i) add(s,i,a[i],0);
for (int i=1; i<=m; ++i)
for (int j=1; j<=n; ++j) add(i,j+m,inf,c[i][j]*off);
for (int i=1; i<=n; ++i) add(i+m,t,b[i],0);
}
int main()
{
read(m);read(n);
for (int i=1; i<=m; ++i) read(a[i]);
for (int i=1; i<=n; ++i) read(b[i]);
for (int i=1; i<=m; ++i)
for (int j=1; j<=n; ++j) read(c[i][j]);
build(1);
while (spfa()) update();
write(ans),puts("");
build(-1);
while (spfa()) update();
write(-ans),puts("");
return 0;
}