题目描述
GG 公司有 nn 个沿铁路运输线环形排列的仓库,每个仓库存储的货物数量不等。如何用最少搬运量可以使 nn 个仓库的库存数量相同。搬运货物时,只能在相邻的仓库之间搬运。
输入格式
文件的第 11 行中有 11 个正整数 nn,表示有 nn 个仓库。
第 22 行中有 nn 个正整数,表示 nn 个仓库的库存量。
输出格式
输出最少搬运量。
输入输出样例
输入 #1复制
5 17 9 14 16 4
输出 #1复制
11
说明/提示
1≤n≤100
思路:(一些其他的解法)
建了个如下的图
ac代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<vector>
#include<unordered_map>
#define mod (1000000007)
using namespace std;
typedef long long ll;
const int MAX = 2e5 + 5;
const int inf = 0x3f3f3f3f;
struct node {
int v,f,w,nxt;
} e[50005<<2];
int n,m,N;
int head[MAX],d[MAX],vis[MAX],tot=1,p[MAX];
void add(int u,int v,int f,int cost=0) {
e[++tot].v = v;e[tot].f = f;e[tot].w = cost;e[tot].nxt = head[u];head[u] = tot;
e[++tot].v = u;e[tot].f = 0; e[tot].w = -cost;e[tot].nxt = head[v];head[v] = tot;
}
bool bfs(int s,int t) {
for(int i = 0; i<=N; i++)
d[i]=inf,vis[i]=0;
d[s]=0;
queue<int>q;
q.push(s);
while(!q.empty()) {
int u=q.front();
q.pop();
vis[u]=0;
for(int i=head[u]; ~i; i=e[i].nxt) {
int j=e[i].v;
if(e[i].f&&d[j]>d[u]+e[i].w) {
d[j]=d[u]+e[i].w;
p[j]=i;
if(!vis[j])vis[j]=1,q.push(j);
}
}
}
return d[t]<inf;
}
int MCMF(int s,int t,int &flow) {
int ans=0;
while(bfs(s,t)) {
int x=t,f=inf;
while(x!=s) {
f = min(f,e[p[x]].f),x=e[p[x]^1].v;
}
flow += f;
ans+=1LL*d[t]*f;
x=t;
while(x!=s) {
e[p[x]].f-=f,e[p[x]^1].f+=f;
x=e[p[x]^1].v;
}
}
return ans;
}
int main() {
scanf("%d",&n);
int st=n,ed=n+1,fl=0,x;N=ed;
for(int i=0;i<=ed;i++) head[i]=-1;
int sum=0;
for(int i=0;i<n;i++){
scanf("%d",&x);
sum+=x;
add(st,i,x,0);
}
for(int i=0;i<n;i++){
add(i,(i+1)%n,inf,1);
add(i,(i-1+n)%n,inf,1);
}
sum/=n;
for(int i=0;i<n;i++){
add(i,ed,sum,0);
}
printf("%d\n",MCMF(st,ed,fl));
return 0 ;
}