KM模版题。
#include <cstdlib> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <fstream> #include <iostream> #define rep(i, l, r) for(int i=l; i<=r; i++) #define N 123 #define MAX 1<<30 #define ll long long #define clr(x, c) memset(x, c, sizeof(x)) using namespace std; int read() { int x=0, f=1; char ch=getchar(); while (ch<‘0‘ || ch>‘9‘) { if (ch==‘-‘) f=-1; ch=getchar(); } while (ch>=‘0‘ && ch<=‘9‘) { x=x*10+ch-‘0‘; ch=getchar(); } return x*f; } struct point{int x, y;} wx[N], wy[N]; int n, m, nx, ny, v[N][N], l[N], st[N], lx[N], ly[N]; bool vx[N], vy[N]; char s[N]; bool Find(int x) { vx[x]=1; rep(y, 1, ny) if (!vy[y]) { int a=lx[x]+ly[y]-v[x][y]; if (!a) { vy[y]=1; if (!l[y] || Find(l[y])) { l[y]=x; return true; } } else st[y]=min(st[y], a); } return false; } int KM() { clr(ly, 0); clr(l, 0); rep(i, 1, nx) lx[i]=-MAX; rep(i, 1, nx) rep(j, 1, ny) if (v[i][j]>lx[i]) lx[i]=v[i][j]; rep(i, 1, nx) { rep(j, 1, ny) st[j]=MAX; while (1) { clr(vx, 0); clr(vy, 0); if (Find(i)) break; int a=MAX; rep(j, 1, ny) if (!vy[j] && a>st[j]) a=st[j]; rep(j, 1, nx) if (vx[j]) lx[j]-=a; rep(j, 1, ny) if (vy[j]) ly[j]+=a; else st[j]-=a; } } int ans=0; rep(i, 1, ny) ans+=v[l[i]][i]; return ans; } int main() { while (~scanf("%d%d", &n, &m) && (n||m)) { nx=ny=0; rep(i, 1, n) { scanf("%s", s); rep(j, 1, m) if (s[j-1]==‘m‘) nx++, wx[nx].x=i, wx[nx].y=j; else if (s[j-1]==‘H‘) ny++, wy[ny].x=i, wy[ny].y=j; } rep(i, 1, nx) rep(j, 1, ny) v[i][j]=-(abs(wx[i].x-wy[j].x)+abs(wx[i].y-wy[j].y)); printf("%d\n", -KM()); } return 0; }
原文:http://www.cnblogs.com/NanoApe/p/4382047.html