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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
|
#include<cstdio> #include<queue> #include<cstring> #include<iostream> using namespace std; const int N=204; const int inf=0x3f3f3f3f; struct E { int to; int cap; int cost; int Next; }edge[N*N<<1]; int tot,head[N]; int n; int s,t; int dis[N],incf[N],pre[N]; bool inqueue[N]; int stock[N]; void init(); inline void add_edge(int,int,int,int); bool SPFA(); int MCMF(); int main() { cin>>n; init(); int i; for(i=1;i<=n;i++) scanf("%d",stock+i); int average=0; for(i=1;i<=n;i++) average+=stock[i]; average/=n; for(i=1;i<=n;i++) { if(stock[i]>average) add_edge(s,i,stock[i]-average,0); else if(stock[i]<average) add_edge(i,t,average-stock[i],0); } for(i=1;i<=n;i++) { if(i==1) { add_edge(1,n,inf,1); add_edge(n,1,inf,1); } else { add_edge(i,i-1,inf,1); add_edge(i-1,i,inf,1); } } cout<<MCMF()<<endl; return 0; } void init() { memset(head,-1,sizeof(head)); s=0; t=n+1; tot=1; } inline void add_edge(int u,int v,int cap,int cost) { tot++; edge[tot].to=v; edge[tot].cap=cap; edge[tot].cost=cost; edge[tot].Next=head[u]; head[u]=tot; tot++; edge[tot].to=u; edge[tot].cap=0; edge[tot].cost=-cost; edge[tot].Next=head[v]; head[v]=tot; } bool SPFA() { queue<int>q; memset(dis,inf,sizeof(dis)); memset(inqueue,0,sizeof(inqueue)); q.push(s); dis[s]=0; inqueue[s]=1; incf[s]=inf; while(!q.empty()) { int x=q.front(); q.pop(); inqueue[x]=0; for(register int i=head[x];~i;i=edge[i].Next) { if(!edge[i].cap) continue; int y=edge[i].to; if(dis[y]>dis[x]+edge[i].cost) { dis[y]=dis[x]+edge[i].cost; incf[y]=min(incf[x],edge[i].cap); pre[y]=i; if(!inqueue[y]) { inqueue[y]=1; q.push(y); } } } } if(dis[t]==inf) return 0; else return 1; } int MCMF() { int maxflow,mincost; maxflow=mincost=0; while(SPFA()) { int x=t; while(x!=s) { int y=pre[x]; edge[y].cap-=incf[t]; edge[y^1].cap+=incf[t]; x=edge[y^1].to; } maxflow+=incf[t]; mincost+=dis[t]*incf[t]; } return mincost; }
|