跳到正文

题解

题解:P10943 Going Home

wanganze约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年3月20日
更新
2026年3月20日
篇幅
约 5 分钟
题目
P10943

版本

  1. v2当前
  2. v1

题意

有一个 n×mn\times m 的地图,上面有 kk 个人和 kk 个房子,人移动一格需要 11 的旅行费,问把所有人送进不同房子的最小费用。每个格子可以同时有多个人。保证 n,m,k≤100n,m,k\le 100。

有多组数据。

分析

观察题意得到这是一个一一对应的问题,可以建模成二分图:人和房子是不交的,我们在人和房子间连边,边权为它们的距离。这样问题就转化为二分图最小权匹配。由于数据范围较小,可以使用费用流解决。

费用流解决二分图带权匹配的方法

建立源点 SS 和汇点 TT。

  1. SS 向左部图的点连流量为 11,费用为 00 的边。
  2. 右部图的点向 TT 连流量为 11,费用为 00 的边。
  3. 在左部图的点和右部图的点之间按需连边,流量为 11,费用为边权(如果是最大权匹配可以边权为负)。
  4. 跑最小费用最大流。最大流量就是最大匹配数,费用是最小/最大权。

实现

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 210;
const LL INF = 0x3f3f3f3f3f3f3f3fll;
struct edge
{
	LL x,cap,cost,rev;
};
vector<edge> e[N];
int n,m,s,t;
bool st[N];
LL d[N];
int it[N];
void add(int a,int b,LL c,LL d)
{
	e[a].push_back({b,c,d,(LL)e[b].size()});
	e[b].push_back({a,0,-d,(LL)e[a].size() - 1});
}
void spfa()
{
	memset(d,0x3f,sizeof d);
	queue<int> q;
	d[s] = 0;
	q.push(s);
	st[s] = 1;
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		st[u] = 0;
		for(auto t : e[u])
			if(t.cap > 0 && d[t.x] > d[u] + t.cost)
			{
				d[t.x] = d[u] + t.cost;
				if(!st[t.x]) q.push(t.x),st[t.x] = 1;
			}
	}
}
LL res;
LL dfs(int u,LL f)
{
	if(u == t) return f;
	st[u] = 1;
	for(int &i = it[u]; i < e[u].size(); i ++)
	{
		edge &t = e[u][i];
		if(!st[t.x] && d[u] + t.cost == d[t.x] && t.cap > 0)
		{
			LL d = dfs(t.x,min(f,t.cap));
			if(d > 0)
			{
				t.cap -= d;
				e[t.x][t.rev].cap += d;
				res += d * t.cost;
				st[u] = 0;
				return d;
			}
		}
	}
	st[u] = 0;
	return 0;
}
LL dinic()
{
	LL flow = 0;
	while(1)
	{
		spfa();
		if(d[t] == INF) break;
		memset(it,0,sizeof it);
		LL d = dfs(s,1e18);
		while(d > 0)
		{
			flow += d;
			d = dfs(s,1e18);
		}
	}
	return flow;
}
const int M = 110;
char g[M][M];
int idx1,idx2;
pair<int,int> a[M],b[M];
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n,m;
	while(cin>>n>>m,n || m)
	{
		for(int i = 1; i <= n; i ++) cin>>g[i] + 1;
		s = 0,t = 201;
		int cnt = 0;
		for(int i = 1; i <= n; i ++)
			for(int j = 1; j <= m; j ++) cnt += g[i][j] == 'm';
		for(int i = 1; i <= n; i ++)
			for(int j = 1; j <= m; j ++)
				if(g[i][j] == 'm') add(s,++ idx1,1,0),a[idx1] = {i,j};
				else if(g[i][j] == 'H') add(++ idx2 + cnt,t,1,0),b[idx2] = {i,j};
		for(int i = 1; i <= cnt; i ++)
			for(int j = 1; j <= cnt; j ++) add(i,j + cnt,1,abs(a[i].first - b[j].first) + abs(a[i].second - b[j].second));
		dinic();
		cout<<res<<'\n';
		res = idx1 = idx2 = 0;
		for(int i = s; i <= t; i ++) e[i].clear();
	}
	return 0;
}
原文