二分图带权最大匹配模板题
我们可以很轻松的想到每一个人到每一个房子之间只有一条最短路径,也就是每一个人到每一个房子之间有一条边,且每一个人都要走一条边,即二分图最大匹配,又要求最短路径,就是每个边加上权值,也就是二分图带权最大匹配
我们用费用流解决
在起点到人之间连边,人到房子之间连边,房子到汇点之间连边即可
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
#define N 100010
#define INF 0x3f3f3f3f
int n,m,s,t;
int head[N],nex[N<<1],e[N<<1],w[N<<1],cost[N<<1],tot;
int v[N],incf[N],pre[N],ans,d[N],maxflow;
char a[110][110];
vector< pair<int,int> >people,house;
void add(int x,int y,int z,int c){
e[++tot]=y,w[tot]=z,nex[tot]=head[x],head[x]=tot,cost[tot]=c;
e[++tot]=x,w[tot]=0,nex[tot]=head[y],head[y]=tot,cost[tot]=-c;
}
bool bfs(){
memset(v,0,sizeof v);
memset(d,0x3f,sizeof d);
d[s]=0;
queue<int>q;
q.push(s);v[s]=1;
incf[s]=INF;
while(q.size()){
int x=q.front();q.pop();
v[x]=0;
for(int i=head[x];i;i=nex[i]){
if(w[i]){
int y=e[i];
if(d[y]>d[x]+cost[i]){
d[y]=d[x]+cost[i];
incf[y]=min(incf[x],w[i]);
pre[y]=i;
if(!v[y]) v[y]=1,q.push(y);
}
}
}
}
if(d[t]==d[0]) return 0;
return 1;
}
void update(){
int x=t;
while(x!=s){
int i=pre[x];
w[i]-=incf[t];
w[i^1]+=incf[t];
x=e[i^1];
}
maxflow+=incf[t];
ans+=d[t]*incf[t];
}
int get(int i,int j){
return (i-1)*m+j+2;
}
int main()
{
while(cin>>n>>m,n||m) {
memset(head,0,sizeof head);
tot = 1;maxflow=0,ans=0,s=1,t=2;
people.clear();house.clear();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++) {
cin >> a[i][j];
if(a[i][j]=='m') people.push_back({i,j});
if(a[i][j]=='H') house.push_back({i,j});
}
for(int i=0;i<people.size();i++)
for(int j=0;j<house.size();j++){
add(get(people[i].first,people[i].second),get(house[j].first,house[j].second),1,abs(people[i].first-house[j].first)+abs(people[i].second-house[j].second));
}
for(int i=0;i<people.size();i++)
add(1,get(people[i].first,people[i].second),1,0);
for(int i=0;i<house.size();i++)
add(get(house[i].first,house[i].second),2,1,0);
while (bfs()) update();
cout << ans << endl;
}
return 0;
}