Test instructions: N boxes with chocolates in the box, each time you can move the chocolate to the adjacent position box, ask the minimum number of moves, so that each box has a maximum of one chocolate.
Idea: Build a picture that connects the chocolate that needs to move and the empty box between the edges.
#include <cstdio>#include <iostream>#include <algorithm>#include <cmath>#include <set>#include <map>#include <string>#include <cstring>#include <stack>#include <queue>#include <vector>#include <cstdlib>#define Lson (rt<<1), L,m#define Rson (rt<<1|1), M+1,r#define M ((l+r) >>1)#define CL (A, B) memset (A,b,sizeof (a));#define LL Long Long#define P pair<int,int>#define X First#define Y Second#define PB Push_back#define FREAD (ZCC) freopen (ZCC, "R", stdin)#define FWRITE (ZCC) freopen (ZCC, "w", stdout)using namespace STD;Const intmaxn=505;Const intinf=9999999;intW[MAXN][MAXN];intLINKER[MAXN],LX[MAXN],LY[MAXN],SLACK[MAXN];BOOLVISX[MAXN],VISY[MAXN];intNx,ny;BOOLDfsintx) {visx[x]=true; for(inty=0; y<ny;y++) {if(Visy[y])Continue;intTmp=lx[x]+ly[y]-w[x][y];if(tmp==0) {visy[y]=true;if(linker[y]==-1|| DFS (Linker[y])) {linker[y]=x;return true; } }Else if(slack[y]>tmp) {slack[y]=tmp; } }return false;}intKM () {cl (linker,-1); Cl (ly,0); for(intI=0; i<nx;i++) {lx[i]=-inf; for(intj=0; j<ny;j++)if(W[i][j]>lx[i]) {LX[I]=W[I][J]; } } for(intx=0; x<nx;x++) {Fill (slack,slack+ny+1, INF); while(true) {cl (VISX,false); CL (Visy,false);if(Dfs (x)) Break;intD=inf; for(intI=0; i<ny;i++)if(!visy[i]&&slack[i]<d) {D=slack[i]; } for(intI=0; i<nx;i++)if(Visx[i]) {Lx[i]-=d; } for(intI=0; i<ny;i++)if(Visy[i]) Ly[i]+=d;ElseSlack[i]-=d; } }intans=0; for(intI=0; i<ny;i++)if(linker[i]!=-1) {Ans+=w[linker[i]][i]; }returnAns;}intA[MAXN];inline int ABS(intx) {returnx<0?-x:x;}intMain () {intN while(~scanf("%d", &n)) { for(intI=0; i<n;i++) {scanf("%d", &a[i]); } for(intI=0; i<n;i++) { for(intj=0; j<n;j++) {w[i][j]=-inf; }} nx=ny=0; for(intI=0; i<n;i++)if(a[i]>1){ for(intj=1; j<a[i];j++) {//To move more out of the for(intk=0; k<n;k++)if(a[k]==0) {W[nx][k]=-min (ABS(i-k), N-ABS(i-k)); } nx++; }} ny=n;printf("%d\n",-km ()); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hdu2282chocolate (km matches)