UVA - 1045 The Great Wall Game(二分图最佳完美匹配)
Posted wzzkaifa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA - 1045 The Great Wall Game(二分图最佳完美匹配)相关的知识,希望对你有一定的参考价值。
题目大意:给出棋盘上的N个点的位置。如今问将这些点排成一行或者一列。或者对角线的最小移动步数(每一个点都仅仅能上下左右移动。一次移动一个)
解题思路:暴力+二分图最佳完美匹配
#include <cstdio>
#include <cstring>
#define N 20
#define INF 0x3f3f3f3f
#define abs(x) ((x) > 0 ? (x) : (-(x)))
#define max(a,b)((a)>(b)?(a):(b))
#define min(a,b)((a)<(b)?(a):(b))
struct Node {
int x, y;
}node[N];
int w[N][N], left[N], Lx[N], Ly[N], slack[N];
int ans, n;
bool S[N], T[N];
bool match(int i) {
S[i] = true;
for (int j = 1; j <= n; j++) {
if (Lx[i] + Ly[j] == w[i][j] && !T[j]) {
T[j] = true;
if (!left[j] || match(left[j])) {
left[j] = i;
return true;
}
}
else slack[j] = min(slack[j], Lx[i] + Ly[j] - w[i][j]);
}
return false;
}
void update() {
int a = 1 << 30;
for (int i = 1; i <= n; i++) if (S[i])
for (int j = 1; j <= n; j++) if (!T[j])
a = min(a, Lx[i] + Ly[i] - w[i][j]);
for (int i = 1; i <= n; i++) {
if (S[i]) Lx[i] -= a;
if (T[i]) Ly[i] += a;
}
}
void KM() {
for (int i = 1; i <= n; i++) {
left[i] = Ly[i] = 0;
Lx[i] = -INF;
for (int j = 1; j <= n; j++)
Lx[i] = max(Lx[i], w[i][j]);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
slack[j] = INF;
for (;;) {
for (int j = 1; j <= n; j++) S[j] = T[j] = 0;
if (match(i)) break;
int a = INF;
for (int j = 1; j <= n; j++)
if (!T[j])
a = min(a, slack[j]);
for (int j = 1; j <= n; j++) {
if (S[j]) Lx[j] -= a;
if (T[j]) Ly[j] += a;
}
}
}
int t = 0;
for (int i = 1; i <= n; i++)
t += Lx[i] + Ly[i];
ans = max(ans, t);
}
void init() {
for (int i = 1; i <= n; i++)
scanf("%d%d", &node[i].x, &node[i].y);
}
int cas = 1;
void solve() {
ans = -INF;
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
w[i][k] = abs(node[i].x - j) + abs(node[i].y - k);
w[i][k] = -w[i][k];
}
}
KM();
}
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++) {
w[i][k] = abs(node[i].x - k) + abs(node[i].y - j);
w[i][k] = -w[i][k];
}
KM();
}
for (int j = 1; j <= n; j++)
for (int i = 1; i <= n; i++) {
w[i][j] = abs(node[i].x - j) + abs(node[i].y - j);
w[i][j] = -w[i][j];
}
KM();
for (int j = 1; j <= n; j++)
for (int i = 1; i <= n; i++) {
w[i][j] = abs(node[i].x - j) + abs(node[i].y - (n - j + 1));
w[i][j] = -w[i][j];
}
KM();
printf("Board %d: %d moves required.\n\n", cas++, abs(ans));
}
int main() {
while (scanf("%d", &n) != EOF && n) {
init();
solve();
}
return 0;
}
以上是关于UVA - 1045 The Great Wall Game(二分图最佳完美匹配)的主要内容,如果未能解决你的问题,请参考以下文章
Fixing the Great Wall UVA - 1336(区间dp)
UVa 1336 Fixing the Great Wall (区间DP)