【网络流24题】负载平衡(费用流)
题面
题解
很简单的题面呀
源点向每个点连边,容量为货物量,费用为0
因为最后要每个仓库的货物都相同
所以从每个仓库向汇点连边,费用为0,容量为平均数
因为可以丢到相邻的仓库
所以向相邻的仓库连边,费用为1,容量为INF
然后就是费用流
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MAXL 500000
#define MAX 5000
#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;
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 sum,a[MAX];
int main()
{
freopen("overload.in","r",stdin);
freopen("overload.out","w",stdout);
n=read();
S=0;T=n+1;
for(int i=1;i<=n;++i)sum+=a[i]=read();
for(int i=1;i<=n;++i)Add(S,i,a[i],0);
for(int i=1;i<=n;++i)Add(i,T,sum/n,0);
for(int i=1;i<n;++i)Add(i,i+1,INF,1);Add(n,1,INF,1);
for(int i=2;i<=n;++i)Add(i,i-1,INF,1);Add(1,n,INF,1);
while(SPFA());
printf("%d
",Cost);
return 0;
}