1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<queue> using namespace std;
const int CP=101*10; const int CE=CP*CP;
const int INF=0x3f3f2f3f;
int read(){ int s=0,ne=1; char c=getchar(); for(;c<'0'||c>'9';c=getchar()) if(c=='-') ne=-1; for(;c>='0'&&c<='9';c=getchar()) s=(s<<1)+(s<<3)+c-'0'; return s*ne; }
class fs{ public: int from,to,nxt,flow,cap,cost; void init(int f,int t,int n,int w,int c,int s) {from=f; to=t; nxt=n; flow=w; cap=c; cost=s;} }E[CE]; int hd[CP],ecnt=1; void _add(int x,int y,int c,int w){ E[++ecnt].init(x,y,hd[x],0,c,w); hd[x] = ecnt; } void add(int x,int y,int c,int w){ _add(x,y,c,w); _add(y,x,0,-w); }
int n,_a,s,t; int a[CP];
int maxflow=0,mincost=0; int d[CP],rst[CP],prv[CP]; bool ins[CP];
bool Augment(int _s,int _t){ memset(d,0x3f,sizeof(d)); memset(ins,false,sizeof(ins)); memset(prv,0,sizeof(prv)); memset(rst,0x3f,sizeof(rst)); queue<int>Q; Q.push(_s); d[_s] = 0; ins[_s] = true; while(!Q.empty()) { int u = Q.front(); Q.pop(); ins[u] = false; for(int k=hd[u]; k; k=E[k].nxt) { fs e=E[k]; if(e.cap-e.flow>0 && d[e.to]>d[u]+e.cost){ d[e.to] = d[u]+e.cost; prv[e.to] = k; rst[e.to] = min(rst[u], e.cap-e.flow); if(!ins[e.to]) Q.push(e.to),ins[e.to] = true; } } } return d[_t] < INF; } void update(int _s,int _t,int r){ int pos=_t; while(pos != _s){ E[prv[pos]].flow += r; E[prv[pos]^1].flow -= r; pos = E[prv[pos]].from; } } void mcmf(int _s,int _t){ while(Augment(_s, _t)){ maxflow += rst[_t]; mincost += d[_t]*rst[_t]; update(_s,_t, rst[_t]); } }
int main() { n=read(); for(int i=1;i<=n;i++) a[i]=read(),_a+=a[i]; _a /= n; s=n+1; t=n+2; for(int i=1;i<=n;i++) if(a[i] > _a) add(s,i, a[i]-_a, 0); else add(i,t, _a-a[i], 0); for(int i=2;i<n;i++){ add(i,i+1, INF, 1); add(i,i-1, INF, 1); } add(1,n, INF, 1); add(1,2, INF, 1); add(n,1, INF, 1); add(n,n-1, INF, 1); mcmf(s,t); printf("%d",mincost); return 0; }
|