Description
求 \(2\times N\) 个点的带权二分图最佳匹配。
\(1\leq N\leq 20\)
Solution
我还是太菜了啊...到现在才学 \(KM\) 。
Code
//It is made by Awson on 2018.3.8
#include <bits/stdc++.h>
#define LL long long
#define dob complex<double>
#define Abs(a) ((a) < 0 ? (-(a)) : (a))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
#define writeln(x) (write(x), putchar('\n'))
#define lowbit(x) ((x)&(-(x)))
using namespace std;
const int N = 20, INF = ~0u>>1;
void read(int &x) {
char ch; bool flag = 0;
for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
x *= 1-2*flag;
}
void print(int x) {if (x > 9) print(x/10); putchar(x%10+48); }
void write(int x) {if (x < 0) putchar('-'); print(Abs(x)); }
int n, a[N+5][N+5], x;
int vis1[N+5], vis2[N+5], E1[N+5], E2[N+5], sla[N+5], match[N+5];
bool dfs(int u) {
vis1[u] = 1;
for (int i = 1; i <= n; i++)
if (vis2[i] == 0) {
int tmp = E1[u]+E2[i]-a[u][i];
if (tmp == 0) {
vis2[i] = 1;
if (match[i] == 0 || dfs(match[i])) {
match[i] = u; return true;
}
}else sla[i] = Min(sla[i], tmp);
}
return false;
}
int KM() {
for (int i = 1; i <= n; i++) {
E1[i] = E2[i] = match[i] = 0;
for (int j = 1; j <= n; j++) E1[i] = Max(E1[i], a[i][j]);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) sla[j] = INF;
while (1) {
for (int j = 1; j <= n; j++) vis1[j] = vis2[j] = 0;
if (dfs(i)) break;
int tmp = INF;
for (int j = 1; j <= n; j++) if (vis2[j] == 0) tmp = Min(tmp, sla[j]);
for (int j = 1; j <= n; j++) {
if (vis1[j]) E1[j] -= tmp;
if (vis2[j]) E2[j] += tmp; else sla[j] -= tmp;
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) ans += a[match[i]][i];
return ans;
}
void work() {
read(n);
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) read(a[i][j]);
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) read(x), a[j][i] *= x;
writeln(KM());
}
int main() {
work(); return 0;
}