题目传送门: POJ 2195

给一张图,图上标记号小人与房子,小人的数目等于房子的数目,要求每个小人都走入不同的房子,小人能够水平或者竖直移动,每移动一格花费一,可以走过房子而不进入,问最小的花费。

KM模板题,用最大权匹配做,把边权变为负值就变成了最小权匹配。

###Code

POJ 2195
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//By Brickgao
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

const int size = 160;
const int INF = 1000000000;

typedef struct pos{
int x, y;
} pos;

bool map[size][size];
bool xckd[size], yckd[size];
int match[size];
pos peo[size], house[size];

bool DFS(int ,const int);

void KM_Perfect_Match(const int n, const int edge[][size])
{
int i, j;
int lx[size], ly[size];
for(i = 0; i < n; i++)
{
lx[i] = -INF;
ly[i] = 0;
for(j = 0; j < n; j++)
lx[i] = max(lx[i], edge[i][j]);
}
bool perfect = false;
while(!perfect)
{
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
if(lx[i] + ly[j] == edge[i][j])
map[i][j] = true;
else
map[i][j] = false;
int live = 0;
memset(match, -1, sizeof(match));
for(i = 0; i < n; i++)
{
memset(xckd, false, sizeof(xckd));
memset(yckd, false, sizeof(yckd));
if(DFS(i, n)) live++;
else
{
xckd[i] = true;
break;
}
}
if(live == n) perfect = true;
else
{
int ex = INF;
for(i = 0; i < n; i++)
for(j = 0; xckd[i] && j < n; j++)
if(!yckd[j]) ex = min(ex, lx[i] + ly[j] - edge[i][j]);
for(i = 0; i < n; i++)
{
if(xckd[i]) lx[i] -= ex;
if(yckd[i]) ly[i] += ex;
}
}
}
}

bool DFS(int p, const int n)
{
int i;
for(i = 0; i < n; i++)
{
if(!yckd[i] && map[p][i])
{
yckd[i] = true;
int t = match[i];
match[i] = p;
if(t == -1 || DFS(t, n))
return true;
match[i] = t;
if(t != -1) xckd[t] = true;
}
}
return false;
}

int main()
{
int n, m, edge[size][size], peonum, housenum;
char s[150];
while(scanf("%d%d", &n, &m) != EOF && n && m)
{
peonum = housenum = 0;
for(int i = 0; i < n; i++)
{
scanf("%s", s);
for(int j = 0; j < m; j++)
{
if(s[j] == 'H')
{
peo[peonum].x = i;
peo[peonum].y = j;
peonum ++;
}
if(s[j] == 'm')
{
house[housenum].x = i;
house[housenum].y = j;
housenum ++;
}
}
}
for(int i = 0; i < peonum; i++)
for(int j = 0; j < peonum; j++)
{
edge[i][j] = 0 - abs(peo[i].x - house[j].x) - abs(peo[i].y - house[j].y);
}
KM_Perfect_Match(peonum, edge);
int cost = 0;
for(int i = 0; i < peonum; i++)
cost += edge[match[i]][i];
printf("%d\n", - cost);
}
return 0;
}