题目:
题解:
拆点,源点向每个仓库连容量为r[i],费用为0的边;每个点向汇点连容量为r[i]平均数,费用为0的边
!!注意:每个x[i]要向y[i]连边,每个y[i]向x[i]连容量INF,费用为1的边,因为不止转手一次
喵喵喵一开始有一个奇怪的想法:把x[i]向y[i]连边而不是y[i]向x[i]连边;这样的问题在于如果上一位来的流量大于汇点需要的平均值,多余的就没处去了,所以必须形成一段流
代码:
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#define INF 1e9
using namespace std;
const int N=305;
int a[N],tot=-1,nxt[N*4+5],point[N],v[N*4+5],c[N*4+5],remind[N*4+5],last[N*4+5],dis[N],mincost;
bool vis[N];
void addline(int x,int y,int cap,int cc)
{
++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=cc; remind[tot]=cap;
++tot; nxt[tot]=point[y]; point[y]=tot; v[tot]=x; c[tot]=-cc; remind[tot]=0;
}
int addflow(int s,int t)
{
int now=t,ans=INF;
while (now!=s)
{
ans=min(ans,remind[last[now]]);
now=v[last[now]^1];
}
now=t;
while (now!=s)
{
remind[last[now]]-=ans;
remind[last[now]^1]+=ans;
now=v[last[now]^1];
}
return ans;
}
bool bfs(int s,int t)
{
queue<int>q;
memset(dis,0x7f,sizeof(dis));
dis[s]=0;
memset(vis,0,sizeof(vis));
q.push(s);
while (!q.empty())
{
int x=q.front();q.pop();vis[x]=0;
for (int i=point[x];i!=-1;i=nxt[i])
if (dis[v[i]]>dis[x]+c[i] && remind[i])
{
dis[v[i]]=dis[x]+c[i];
last[v[i]]=i;
if (!vis[v[i]]) vis[v[i]]=1,q.push(v[i]);
}
}
if (dis[t]>INF) return 0;
int flow=addflow(s,t);
mincost+=flow*dis[t];
return 1;
}
int main()
{
memset(nxt,-1,sizeof(nxt));
memset(point,-1,sizeof(point));
int sum=0,n;
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]),sum+=a[i];
sum/=n;
for (int i=1;i<=n;i++)
{
addline(0,i,a[i],0);
addline(i+n,n*2+1,sum,0);
addline(i,i+n,INF,0);
int x=i-1,y=i+1;
if (x==0) x=n;if (y>n) y=1;
addline(x+n,i,INF,1);
addline(y+n,i,INF,1);
}
while (bfs(0,2*n+1));
printf("%d",mincost);
}