题解:
很裸的一道最小费用流。
求一下平均数,然后原数-=平均数。
若得到值为正,则从$S$向该点连一条流量为得到值,费用为$0$的边,
若为负,则从该点连一条流量为得到值绝对值,费用为$0$的边。
然后相邻的点互相建流量$inf$,费用为$1$的边。
然后最小费用最大流裸上。
代码:
#include<queue> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define N 150 #define M 5*N #define ll long long const int inf = 0x3f3f3f3f; const ll Inf = 0x3f3f3f3f3f3f3f3fll; inline int rd() { int f=1,c=0;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){c=10*c+ch-'0';ch=getchar();} return f*c; } int n,S,T,hed[N],cnt=-1; ll a[N],lim; struct EG { int to,nxt; ll w,c; }e[M]; void ae(int f,int t,ll w,ll c) { e[++cnt].to = t; e[cnt].nxt = hed[f]; e[cnt].w = w; e[cnt].c = c; hed[f] = cnt; } queue<int>q; ll dis[N],fl[N]; int fa[N],pre[N]; bool vis[N]; bool spfa() { memset(dis,0x3f,sizeof(dis)); dis[S] = 0,vis[S] = 1,fl[S] = Inf; q.push(S); while(!q.empty()) { int u = q.front(); q.pop(); for(int j=hed[u];~j;j=e[j].nxt) { int to = e[j].to; if(e[j].w&&dis[to]>dis[u]+e[j].c) { dis[to] = dis[u]+e[j].c; fl[to] =min(fl[u],e[j].w); pre[to] = j,fa[to] = u; if(!vis[to]) { vis[to] = 1; q.push(to); } } } vis[u]=0; } return dis[T]!=Inf; } ll mc; void mcmf() { while(spfa()) { mc+=dis[T]*fl[T]; int u = T; while(u!=S) { e[pre[u]].w-=fl[T]; e[pre[u]^1].w+=fl[T]; u = fa[u]; } } } int main() { n = rd();S = n+1,T = n+2; memset(hed,-1,sizeof(hed)); for(int i=1;i<=n;i++)a[i]=rd(),lim+=a[i]; lim/=n; for(int i=1;i<=n;i++) { a[i]-=lim; if(a[i]>0) { ae(S,i,a[i],0); ae(i,S,0,0); }else if(a[i]<0) { ae(i,T,-a[i],0); ae(T,i,0,0); } int lf = i==1?n:i-1; int rt = i==n?1:i+1; ae(i,lf,Inf,1); ae(lf,i,0,-1); ae(i,rt,Inf,1); ae(rt,i,0,-1); } mcmf(); printf("%lld\n",mc); return 0; }