这一题虽然说是模板题,但作为学习了最小费用最大流过程之后的第一题,模型的建立还是一脸懵比,之后通过见识相关的变形再来磨练建模的能力吧
如下是网上题解中关于本题中网络流的建模:
1.所有人到所有的房子均建容量为1,费用为人到房子的曼哈顿距离的流
2.建立超级源点s,s到所有人均建容量为1,费用为0的流
3.建立超级汇点t,所有房子到t均建容量为1,费用为0的流
#include
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 105*2;
int n,m;
char f[105][105];
struct node{
int x,y;
int dist(node b){
return abs(x - b.x) + abs(y - b.y);
}
}man[105],house[105];
struct Edge{
int from, to, cap, flow, cost;
Edge(int u, int v, int c, int f, int w): from(u),to(v),cap(c),flow(f),cost(w){}
};
struct MCMF{
int n,m;
vector edges;
vector<int> G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void init(int n){
this->n = n;
for(int i = 0; i < n; ++i) G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int cap, int cost){
edges.push_back(Edge(from,to,cap,0,cost));
edges.push_back(Edge(to,from,0,0,-cost));
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool BellmanFord(int s, int t, int& flow, long long& cost){
for(int i = 0; i < n; ++i) d[i] = INF;
memset(inq,0,sizeof(inq));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int>Q;
Q.push(s);
while(!Q.empty()){
int u = Q.front(); Q.pop(); inq[u] = 0;
for(int i = 0; i < G[u].size(); ++i){
Edge& e = edges[G[u][i]];
if(e.cap > e.flow && d[e.to] > d[u] + e.cost){
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u], e.cap - e.flow);
if(!inq[e.to]) { Q.push(e.to); inq[e.to] = 1; }
}
}
}
if(d[t] == INF) return false;
flow += a[t];
cost += (long long)d[t] * (long long)a[t];
for(int u = t; u != s; u = edges[p[u]].from){
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
}
return true;
}
int MincostMaxflow(int s, int t, long long& cost){
int flow = 0; cost = 0;
while(BellmanFord(s, t, flow, cost)) ;
return flow;
}
};
MCMF mc;
int main(){
while(~scanf("%d%d",&n,&m) && (n || m)){
memset(f,0,sizeof(f));
memset(man,0,sizeof(man));
memset(house,0,sizeof(house));
for(int i = 1; i <= n; ++i){
scanf("%s",f[i]+1);
}
int p = 0, q = 0;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
if(f[i][j] == 'm'){
man[p].x = i;
man[p].y = j;
p++;
}
else if(f[i][j] == 'H'){
house[q].x = i;
house[q].y = j;
q++;
}
}
}
mc.init(p+q+2);
for(int i = 0; i < p; ++i){
for(int j = 0 ; j < q; ++j){
mc.AddEdge(i,p+j,1,man[i].dist(house[j]));
}
}
for(int i = 0; i < p; ++i)
mc.AddEdge(p+q,i,1,0);
for(int i = p; i < p+q; ++i)
mc.AddEdge(i,p+q+1,1,0);
long long ans;
mc.MincostMaxflow(p+q,p+q+1,ans);
printf("%lld\n",ans);
}
return 0;
}