题目链接:
题目大意:
给出一张地图,给出人和屋子的位置,问每个人都有屋子住的走的最小的距离之和
题目分析:
首先屋子的数量和人的数量相等,那么每个人一定有屋子住,要求最小的花费,花费就是人到屋子的距离,所以就是一个最优匹配的模板题,当然也可以看做是最小费用最大流的模板题,建图方法也很朴素,就是源点连向所有的人连边,容量为1,花费为0,汇点向所有的屋子连边,容量为1,花费为0,然后每个人到每个屋子的距离作为花费,1作为容量,在人和屋子之间建边
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#define MAX 105
#define INF 0x7fffffff
using namespace std;
int flow[MAX<<1][MAX<<1];
int cost[MAX<<1][MAX<<1];
int map[MAX][MAX];
int pre[MAX<<1],dis[MAX<<1];
int minflow[MAX<<1],mark[MAX<<1];
char str[MAX][MAX];
struct Node
{
int x,y;
}house[MAX],man[MAX];
int spfa ( int start , int end )
{
queue<int> q;
//memset ( dis , 0x3f , sizeof ( dis ));
memset ( mark , 0 , sizeof ( mark ));
memset ( pre , -1 , sizeof ( pre ));
//memset ( minflow , INF , sizeof ( minflow));
for ( int i = 0 ; i < (MAX<<1) ; i++ )
dis[i] = minflow[i] = INF;
q.push ( start );
dis[start] = 0;
mark[start] = 1;
while ( !q.empty())
{
int u = q.front();
q.pop();
mark[u] = 0;
for ( int i = 0 ; i <= end ; i++ )
if (flow[u][i]&& dis[i] > dis[u] + cost[u][i] )
{
dis[i] = dis[u] + cost[u][i];
pre[i] = u;
minflow[i] = min ( minflow[u] , flow[u][i] );
if ( !mark[i] )
{
mark[i] = 1;
q.push ( i );
}
}
}
return dis[end]!= INF;
}
int maxflow_mincost ( int start , int end )
{
int i,x,ans = 0;
while ( spfa(start,end) )
{
x = end;
while ( pre[x] != -1 )
{
flow[pre[x]][x] -= minflow[end];
flow[x][pre[x]] += minflow[end];
x = pre[x];
}
ans += dis[end];
}
return ans;
}
int n,m,k1,k2,t;
int main ( )
{
while (~scanf ( "%d%d" , &n , &m ) , n+m )
{
k1 = k2 = 1;
memset ( flow , 0 , sizeof (flow ) );
for ( int i = 0 ; i < n ; i++ )
{
scanf ( "%s" , str[i] );
for ( int j = 0 ; j < m ; j++ )
{
if ( str[i][j] == 'H' )
{
house[k1].x = i;
house[k1++].y = j;
}
else if ( str[i][j] == 'm')
{
man[k2].x = i;
man[k2++].y = j;
}
}
}
n = k1-1;
for ( int i= 0 ; i < 2*n+1 ; i++)
for ( int j = 0 ; j < 2*n+1 ; j++ )
cost[i][j] = INF;
for ( int i = 1 ; i <= n ; i++ )
{
for ( int j = n+1 ; j < 2*n+1 ; j++ )
{
cost[i][j] = abs ( house[j-n].x - man[i].x )
+abs ( house[j-n].y - man[i].y );
cost[j][i] = -cost[i][j];
flow[i][j] = 1;
}
cost[i][0] =cost[0][i] = 0;
flow[0][i] = 1;
cost[i+n][2*n+1] = cost[2*n+1][i+n] = 0;
flow[i+n][2*n+1] = 1;
}
printf ( "%d\n" , maxflow_mincost( 0 , 2*n+1 ) );
}
}