-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathKuhnMunkres.cc
48 lines (47 loc) · 1.43 KB
/
KuhnMunkres.cc
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
#include <algorithm>
struct KM {
typedef long long cost_t;
static const int N = 1000;
static const cost_t inf = 1e9;
cost_t lx[N], ly[N], sl[N];
int px[N],py[N],sy[N],fa[N],n;
void aug(int v) {
sy[v]=py[v]; if (px[sy[v]]!=-2) aug(px[sy[v]]);
}
bool find(int v, const cost_t w[][N]) {
for (int i=0;i<n;++i) if (!~py[i]) {
if (sl[i]>lx[v]+ly[i]-w[v][i]) {
sl[i]=lx[v]+ly[i]-w[v][i]; fa[i] = v;
}
if (lx[v]+ly[i]==w[v][i]) {
py[i]=v; if (!~sy[i]) {aug(i); return 1;}
if (~px[sy[i]]) continue;
px[sy[i]]=i; if (find(sy[i],w)) return 1;
}
}
return 0;
}
cost_t gao(int _n, const cost_t w[][N], cost_t m=inf) {
n=_n; std::fill(sy,sy+n,-1); std::fill(ly,ly+n,0);
for (int i=0;i<n;++i) lx[i]=*std::max_element(w[i],w[i]+n);
for (int i(0),flag;i<n;++i) {
for (int j=0;j<n;++j)px[j]=py[j]=-1,sl[j]=inf;
px[i]=-2; if (find(i,w)) continue;
for (flag=0,m=inf; !flag; m=inf) {
for (int j=0;j<n;++j) if (!~py[j]) m=std::min(m,sl[j]);
for (int j=0;j<n;++j) {
if (~px[j]) lx[j]-=m;
if (~py[j]) ly[j]+=m;
else sl[j]-=m;
}
for (int j=0;j<n;++j) if (!~py[j]&&!sl[j]) {
py[j]=fa[j]; if (!~sy[j]) {aug(j);flag=1;break;}
px[sy[j]]=j; if (find(sy[j],w)) {flag=1;break;}
}
}
}
cost_t ret(0);
for (int i=0;i<n;++i) ret+=w[sy[i]][i];
return ret;
}
};