Going Home 可以转成最大权匹配,直接套模板…… #include <iostream> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <string> #include <cstdio> #include <climits> #include <queue> #include <map> #include <list> #include <set> #include <vector> using namespace std; char themap[105][105]; int g[105][105]; int H[105][2], M[105][2]; int mH[105], mM[105]; const int MAXN = 105; #define inf 1000000000 #define _clr(x) memset(x,0xff,sizeof(int)*n) int kuhn_munkras(int m,int n,int mat[][MAXN],int* match1,int* match2){ int s[MAXN],t[MAXN],l1[MAXN],l2[MAXN],p,q,ret=0,i,j,k; for (i=0;i<m;i++) for (l1[i]=-inf,j=0;j<n;j++) l1[i]=mat[i][j]>l1[i]?mat[i][j]:l1[i]; for (i=0;i<n;l2[i++]=0); for (_clr(match1),_clr(match2),i=0;i<m;i++){ for (_clr(t),s[p=q=0]=i;p<=q&&match1[i]<0;p++) for (k=s[p],j=0;j<n&&match1[i]<0;j++) if (l1[k]+l2[j]==mat[k][j]&&t[j]<0){ s[++q]=match2[j],t[j]=k; if (s[q]<0) for (p=j;p>=0;j=p) match2[j]=k=t[j],p=match1[k],match1[k]=j; } if (match1[i]<0){ for (i--,p=inf,k=0;k<=q;k++) for (j=0;j<n;j++) if (t[j]<0&&l1[s[k]]+l2[j]-mat[s[k]][j]<p) p=l1[s[k]]+l2[j]-mat[s[k]][j]; for (j=0;j<n;l2[j]+=t[j]<0?0:p,j++); for (k=0;k<=q;l1[s[k++]]-=p); } } for (i=0;i<m;i++) ret+=mat[i][match1[i]]; return ret; } int main() { int n, m, ih, im; while (scanf("%d%d", &n, &m) && (n||m)) { ih = im = 0; for (int i=0; i < n; i++) { scanf("%s", themap[i]); for (int j=0; j < m; j++) { if (themap[i][j] == 'H') { H[ih][0] = i; H[ih++][1] = j; } else if (themap[i][j] == 'm') { M[im][0] = i; M[im++][1] = j; } } } memset(g, 0, sizeof(g)); for (int i=0; i < ih; i++) { for (int j=0; j < im; j++) { g[i][j] =200-( abs(H[i][0] - M[j][0]) + abs(H[i][1] - M[j][1])); } } printf("%d/n", 200*ih-kuhn_munkras(ih, im, g, mH, mM)); } return 0; }