题意:求最小花费。KM通常是来求最大完美匹配,这里只需要把权重变为负数。最后再变回来即可
#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 int maxn=305;
const int inf=999999;
int w[maxn][maxn];
int linker[maxn],lx[maxn],ly[maxn],slack[maxn];
bool visx[maxn],visy[maxn];
int nx,ny;
bool dfs(int x){
visx[x]=true;
for(int y=1;y<=ny;y++){
if(visy[y])continue;
int tmp=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;
}
int km(){
cl(linker,-1);
cl(ly,0);
for(int i=1;i<=nx;i++){
lx[i]=-inf;
for(int j=1;j<=ny;j++)if(w[i][j]>lx[i]){
lx[i]=w[i][j];
}
}
for(int x=1;x<=nx;x++){
fill(slack,slack+ny+1,inf);
while(true){
cl(visx,false);
cl(visy,false);
if(dfs(x))break;
int d=inf;
for(int i=1;i<=ny;i++)if(!visy[i]&&d>slack[i]){
d=slack[i];
}
for(int i=1;i<=nx;i++)if(visx[i]){
lx[i]-=d;
}
for(int i=1;i<=ny;i++)if(visy[i])ly[i]+=d;
else slack[i]-=d;
}
}
int ans=0;
for(int i=1;i<=ny;i++)if(linker[i]!=-1){
ans+=w[linker[i]][i];
}
return ans;
}
char a[maxn][maxn];
P h[maxn],mm[maxn];
inline int abs(int s){return s<0?-s:s;}
int main(){
int n,m;
while(scanf("%d%d",&n,&m)&&n+m){
int num1=1,num2=1;
for(int i=1;i<=n;i++){
scanf("%s",a[i]);
for(int j=0;j<m;j++){
if(a[i][j]==‘H‘){
h[num1].X=i;
h[num1++].Y=j;
}
if(a[i][j]==‘m‘){
mm[num2].X=i;
mm[num2++].Y=j;
}
}
}
//printf("===%d %d\n",num1,num2);
for(int i=1;i<num1;i++){
for(int j=1;j<num2;j++){
w[i][j]=abs(h[i].X-mm[j].X)+abs(h[i].Y-mm[j].Y);
w[i][j]=-w[i][j];
}
}
nx=ny=num2-1;
printf("%d\n",-km());
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-12 01:32:29