P4016 负载平衡问题
P4016 负载平衡问题
费用流问题,题解里有比较优秀的贪心做法,我也就不学习了,写正经的网络流
单节点解决方案
1.对于每个仓库的原始存量va,从源点 -> i建容量为va、费用为0的边,表示不花费每个仓库就已有的
2.对于每个点 -> 汇点建容量为存量平均值,费用为0的边
3.对于每个点向相邻的点连接容量无限费用为1的边,表示转运
在此图上,最大流是等于所有仓库存量和的,而且也保证了仓库存量相等,求解最小花费即可
代码如下
#include<bits/stdc++.h>
using namespace std;
const int maxn = 120;
const int maxm = 1020;
int n,m,str,end,tot = -1,maxflow,mincost,cnt;
int head[maxn],pre[maxn],last[maxn],flow[maxn],d[maxn],temp[maxn];
bool vis[maxn];
struct node
{
int net,va,cost,to;
}data[maxm<<1];
void add(int a,int b,int va,int cost)
{
data[++tot].cost = cost;
data[tot].net = head[a];
data[tot].to = b;
data[tot].va = va;
head[a] = tot;
}
bool SPFA()
{
memset(d,0x3f,sizeof(d));
memset(flow,0x3f,sizeof(flow));
memset(vis,0,sizeof(vis));
queue<int> q;
q.push(str);
vis[str] = 1;
d[str] = 0;
pre[end] = -1;
while(!q.empty())
{
int from = q.front();q.pop();
vis[from] = 0;
for(int i=head[from];i!=-1;i=data[i].net)
{
int to = data[i].to ;
int va = data[i].va ;
int cost = data[i].cost ;
if(va>0&&d[to]>d[from]+cost)
{
d[to] = d[from]+cost;
pre[to] = from;
last[to] = i;
flow[to] = min(flow[from],va);
if(!vis[to])
{
vis[to] = 1;
q.push(to);
}
}
}
}
return pre[end] != -1;
}
void MCMF()
{
while(SPFA())
{
int now = end;
maxflow += flow[end];
mincost += flow[end]*d[end];
while(now!=str)
{
data[last[now]].va -= flow[end];
data[last[now]^1].va += flow[end];
now = pre[now];
}
}
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d",&n);
str = n+1;
end = n+2;
for(int i=1;i<=n;i++)
{
scanf("%d",&temp[i]);
add(str,i,temp[i],0);
add(i,str,0,0);
cnt += temp[i];
}
cnt /= n;
for(int i=1;i<=n;i++)
{
add(i,end,cnt,0);
add(end,i,0,0);
}
for(int i=1;i<=n;i++)
{
int tt = i+1;
if(i==n) tt = 1;
add(i,tt,2e9,1);
add(tt,i,0,-1);
add(tt,i,2e9,1);
add(i,tt,0,-1);
}
MCMF();
printf("%d\n",mincost);
return 0;
}