n boxes in a circle, the first box I have an AI ball, each time you can move a ball from a box into one of the two adjacent boxes. Ask how many times to move so that the number of balls in each box does not exceed 1.
σai<=n.1<=n<=1000.
Minimum cost maximum flow.
Each box as a point.
If the ai>1 is connected to this point from the source point to a capacity of AI, the cost is 0 side.
If the ai=0 is from this point to the meeting point a capacity of 1, the cost of 0 side.
Each box is connected to the adjacent two boxes with a positive infinity capacity and a cost of 1 sides.
The minimum cost maximum flow is the answer.
1#include <cstring>2#include <cstdio>3#include <iostream>4#include <algorithm>5#include <queue>6 using namespacestd;7 Const intdian=1005;8 Const intbian=6005;9 Const intinf=0x3f3f3f3f;Ten intH[dian],nxt[bian],ver[bian],val[bian],cos[bian],with[dian],minn[dian]; One intD[dian],v[dian]; A intMap[dian]; - intN,tot; - ints,t; the voidAddintAintBintCintd) { -tot++;ver[tot]=b;val[tot]=c;cos[tot]=d;nxt[tot]=h[a];h[a]=tot; -tot++;ver[tot]=a;val[tot]=0; cos[tot]=-d;nxt[tot]=h[b];h[b]=tot; - } + BOOLTell () { -memset (V,0,sizeof(v)); +memset (D,0x3f,sizeof(d)); AMemset (with,0,sizeof(with)); atMEMSET (Minn,0x3f,sizeof(Minn)); -queue<int>Q; - Q.push (S); -v[s]=1; -d[s]=0; - while(!Q.empty ()) { in intx=Q.front (); - Q.pop (); tov[x]=0; + for(intI=h[x];i;i=Nxt[i]) { - inty=Ver[i]; the if(d[y]>d[x]+cos[i]&&Val[i]) { *d[y]=d[x]+Cos[i]; $minn[y]=min (minn[x],val[i]);Panax Notoginsengwith[y]=i; - if(!V[y]) { thev[y]=1; + Q.push (y); A } the } + } - } $ if(d[t]==0x3f3f3f3f) $ return 0; - return 1; - } the intZeng () { - for(inti=t;i!=s;i=ver[with[i]^1]){Wuyival[with[i]]-=Minn[t]; theval[with[i]^1]+=Minn[t]; - } Wu returnminn[t]*D[t]; - } About intDinic_cost () { $ intR=0; - while(Tell ()) -r+=Zeng (); - returnR; A } + intMain () { the intCAs; -scanf"%d",&CAs); $ while(cas--){ thememset (H,0,sizeof(h)); thememset (NXT,0,sizeof(NXT)); thetot=1; thescanf"%d",&n); -s=n+1, t=n+2; in for(intI=1; i<=n;i++) thescanf"%d",&map[i]); the for(intI=1; i<=n;i++){ About if(map[i]>1) theAdd (s,i,map[i]-1,0); the Else if(!Map[i]) theAdd (I,t,1,0); +Add (i, (i==1)? n:i-1Inf1); -Add (i, (i==n)?1: i+1Inf1); the }Bayiprintf"%d\n", Dinic_cost ()); the } the return 0; -}
SPOJ 371 Boxes