2 2 .m H. 5 5 HH..m ..... ..... ..... mm..H 7 8 ...H.... ...H.... ...H.... mmmHmmmm ...H.... ...H.... ...H.... 0 0
2 10 28
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #pragma comment (linker,"/STACK:102400000,102400000") #define mod 1000000009 #define INF 0x3f3f3f3f #define pi acos(-1.0) #define eps 1e-6 #define lson rt<<1,l,mid #define rson rt<<1|1,mid+1,r typedef long long ll; using namespace std; /*最小费用最大流,求最大费用只需要取相反数,结果取相反数即可。 点的总数为N,点的编号0~N-1*/ const int MAXN = 300; const int MAXM = 100000; struct Node { int x,y; }H[MAXN],M[MAXN]; struct Edge { int to,next,cap,flow,cost; }edge[MAXM]; int head[MAXN],tol; int pre[MAXN],dis[MAXN]; bool vis[MAXN]; int N,n,m; void init(int n) { N=n; tol=0; memset(head,-1,sizeof(head)); } void addedge(int u,int v,int cap,int cost) { edge[tol].to=v; edge[tol].cap=cap; edge[tol].cost=cost; edge[tol].flow=0; edge[tol].next=head[u]; head[u]=tol++; edge[tol].to=u; edge[tol].cap=0; edge[tol].cost=-cost; edge[tol].flow=0; edge[tol].next=head[v]; head[v]=tol++; } bool spfa(int s,int t) { queue<int>q; for (int i=0;i<N;i++) { dis[i]=INF; vis[i]=false; pre[i]=-1; } dis[s]=0; vis[s]=true; q.push(s); while (!q.empty()) { int u=q.front(); q.pop(); vis[u]=false; for (int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].to; if (edge[i].cap > edge[i].flow && dis[v] > dis[u] + edge[i].cost) { dis[v]=dis[u] + edge[i].cost; pre[v]=i; if (!vis[v]) { vis[v]=true; q.push(v); } } } } if (pre[t]==-1) return false; else return true; } //返回的是最大流,cost存的是最小费用 int minCostMaxflow(int s,int t,int &cost) { int flow=0; cost=0; while (spfa(s,t)) { int Min=INF; for (int i=pre[t];i!=-1;i=pre[edge[i^1].to]) { if (Min > edge[i].cap-edge[i].flow) Min=edge[i].cap-edge[i].flow; } for (int i=pre[t];i!=-1;i=pre[edge[i^1].to]) { edge[i].flow+=Min; edge[i^1].flow-=Min; cost+=edge[i].cost*Min; } flow+=Min; } return flow; } int main() { char ch; while (scanf("%d%d",&n,&m)&&(m||n)) { int hh=1,mm=1; getchar(); for (int i=1;i<=n;i++) { for (int j=1;j<=m;j++) { scanf("%c",&ch); if (ch=='H') { H[hh].x=i; H[hh++].y=j; } else if (ch=='m') { M[mm].x=i; M[mm++].y=j; } } getchar(); } N=hh+mm+2; init(N); mm--,hh--; for (int i=1;i<=mm;i++) addedge(0,i,1,0); for (int i=1;i<=hh;i++) addedge(i+mm,N-1,1,0); for (int i=1;i<=mm;i++) { for (int j=1;j<=hh;j++) { int x=abs(M[i].x-H[j].x)+abs(M[i].y-H[j].y); addedge(i,j+mm,1,x); } } int ans; int y=minCostMaxflow(0,N-1,ans); printf("%d\n",ans); } return 0; }
原文地址:http://blog.csdn.net/u014422052/article/details/45726541