Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15130 | Accepted: 7740 |
Description
Input
Output
Sample Input
2 2 .m H. 5 5 HH..m ..... ..... ..... mm..H 7 8 ...H.... ...H.... ...H.... mmmHmmmm ...H.... ...H.... ...H.... 0 0
Sample Output
2 10 28
Source
#include <stdio.h> #include <string.h> #include <math.h> struct num { int x,y; }h[200],m[200]; int cost[300][300],cap[300][300]; int queue[1000000],status[300],dis[300],pre[300]; int INF=0x7fffffff,sta,end; int main() { int EK(); int i,j,n,u,s,t,top1,top2,x1,y1,x2,y2; char c; while(scanf("%d %d%*c",&n,&u)!=EOF) { if(n==0&&u==0) { break; } top1=top2=0; for(i=1;i<=n;i++) { for(j=1;j<=u;j++) { scanf("%c",&c); if(c=='H') { h[top1].x=i; h[top1++].y= j; }else if(c=='m') { m[top2].x= i; m[top2++].y= j; } } getchar(); } if(top1==0) { printf("0\n"); continue; } memset(cap,0,sizeof(cap)); memset(cost,0,sizeof(cost)); n=top1; for(i=1;i<=n;i++) { cap[0][i]=1; } for(i=1;i<=n;i++) { x1=m[i-1].x; y1=m[i-1].y; for(j=1;j<=n;j++) { x2=h[j-1].x; y2=h[j-1].y; x2= x2- x1; if(x2<0) { x2=-x2; } y2=y2-y1; if(y2<0) { y2=-y2; } cap[i][n+j]=1; cost[i][n+j]=(x2+y2); cost[n+j][i]=-(x2+y2); } } for(i=1;i<=n;i++) { cap[n+i][n+n+1]=1; } s=0; sta=0; end=2*n+1; s=EK(); printf("%d\n",s); } return 0; } int bfs() { int i,j,base,top,x; base=top=0; for(i=0;i<=end;i++) { dis[i]=INF; } memset(status,0,sizeof(status)); queue[top++]=0; status[0]=1; dis[0]=0; while(base<top) { x=queue[base++]; status[x]=0; for(i=1;i<=end;i++) { if(x!=i&&cap[x][i]) { if(dis[i]>(dis[x]+cost[x][i])) { dis[i]=dis[x]+cost[x][i]; pre[i]=x; if(!status[i]) { status[i]=1; queue[top++]=i; } } } } } if(dis[end]==INF) { return 0; }else { return 1; } } int EK() { int i,j,s=0,k,min=INF; while(1) { k=bfs(); if(k==0) { break; } for(i=end; i!=0; i=pre[i]) { j=pre[i]; if(min>cap[j][i]) { min=cap[j][i]; } } for(i=end; i!=0; i=pre[i]) { j=pre[i]; s+=(cost[j][i]*min); cap[j][i]-=min; cap[i][j]+=min; } } return s; }