题目
(戳我)[https://www.luogu.com.cn/problem/solution/P4016]
思路
讲一下费用流的建图,首先我们需要做的肯定是做到数量平均,所以我们考虑大于平均值的边应该是要出流的,小于的应该是要流入的,题目要求的是搬运量,自然而然它就是费用,我们在相邻的仓库也就是可以相互运输的仓库之间建一条边,容量为正无穷,费用为1,然后源点联结所有数量大于平均值的点,边权是差值,小于平均值的点同理,然后我们跑一遍费用流就好了。另外一种做法的话是贪心,一个经典的均摊纸牌问题,贪心大法好,不了解的可以自行百度。
代码实现
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
#define rep(i,f_start,f_end) for (int i=f_start;i<=f_end;++i)
#define per(i,n,a) for (int i=n;i>=a;i--)
#define MT(x,i) memset(x,i,sizeof(x) )
#define rev(i,start,end) for (int i=start;i<end;i++)
#define inf 0x3f3f3f3f
#define mp(x,y) make_pair(x,y)
#define lowbit(x) (x&-x)
#define MOD 1000000007
#define exp 1e-8
#define N 1000005
#define fi first
#define se second
#define pb push_back
typedef long long ll;
typedef vector <int> VI;
typedef pair<int ,int> PII;
typedef pair<int ,PII> PIII;
ll gcd (ll a,ll b) {return b?gcd (b,a%b):a; }
inline int read() {
char ch=getchar(); int x=0, f=1;
while(ch<'0'||ch>'9') {
if(ch=='-') f=-1;
ch=getchar();
} while('0'<=ch&&ch<='9') {
x=x*10+ch-'0';
ch=getchar();
} return x*f;
}
const int maxn=1010;
int n,m,s,t,cnt=1;
int head[maxn],dis[maxn],pre[maxn],incf[maxn];
int maxflow,mincost;
bool vis[maxn];
struct edge {
int v,next,flow,cost;
}e[maxn<<1];
inline void add (int u,int v,int flow,int cost) {
e[++cnt]= (edge) {v,head[u],flow,cost};
head[u]=cnt;
}
inline void add_edge (int u,int v,int flow,int cost) {
add (u,v,flow,cost);
add (v,u,0,-cost);
}
inline bool spfa () {
queue <int > q;
MT (dis,0x3f);
MT (vis,0);
q.push (s);
dis[s]=0;
vis[s]=1;
incf[s]=1<<30;
while (q.size ()) {
int x=q.front (); q.pop ();
vis[x]=0;
for (int i=head[x];i!=-1;i=e[i].next) {
if (!e[i].flow) continue;
int v=e[i].v;
if (dis[v]>dis[x]+e[i].cost) {
dis[v]=dis[x]+e[i].cost;
incf[v]=min (incf[x],e[i].flow);
pre[v]=i;
if (!vis[v]) vis[v]=1,q.push (v);
}
}
}
if (dis[t]==inf) return 0;
return dis[t];
}
inline void mcmf () {
while (spfa ()) {
int x=t;
maxflow+=incf[t];
mincost+=dis[t]*incf[t];
int i;
while (x!=s) {
i=pre[x];
e[i].flow-=incf[t];
e[i^1].flow+=incf[t];
x=e[i^1].v;
}
}
}
int a[maxn];
int main () {
MT (head,-1);
scanf("%d",&n);
int sum=0;
for(int i=1;i<=n;++i) scanf("%d",&a[i]),sum+=a[i];
sum/=n;
for(int i=1;i<=n;++i) {
if(a[i]<sum) {
add_edge(0,i,sum-a[i],0);
} else if(a[i]>sum) {
add_edge(i,n+1,a[i]-sum,0);
}
if(i==1) {
add_edge(1,n,inf,1);
add_edge(n,1,inf,1);
} else {
add_edge(i-1,i,inf,1);
add_edge(i,i-1,inf,1);
}
}
s=0,t=n+1;
mcmf();
printf("%d
",mincost);
return 0;
}