# HDU2255 奔小康赚大钱（二分图最优匹配）

## 奔小康赚大钱

• Time Limit: 1000/1000 MS (Java/Others)
• Memory Limit: 32768/32768 K (Java/Others)
• Total Submission(s): 12293
• Accepted Submission(s): 5409

### Sample Input

2
100 10
15 23

### Sample Output

123

### Source

HDOJ 2008 Summer Exercise（4）- Buffet Dinner

lcy

### 链接

http://acm.hdu.edu.cn/showproblem.php?pid=2255

### 代码

StatusAccepted
Time826ms
Memory2036kB
Length2692
/* match数组记录与右端点连接的左端点
* cx cy为左右端点的顶标
* slack[j]保存跟当前节点j相连的节点i的cx[i]+cy[j]−weight(i,j)的最小值
* visx，visy数组记录是否曾访问过，也是判断是否在增广路上
*/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 310;
const int inf = 0x3f3f3f3f;
int match[maxn], cx[maxn], cy[maxn], slack[maxn];
int G[maxn][maxn]; // 边权
bool visx[maxn], visy[maxn];
int n, nx, ny, ans;

bool find(int x)
{
int tmp;
visx[x] = 1;
for (int y = 0; y < ny; ++y)
{
if (visy[y]) // 如果这个点已经访问过
continue;
tmp = cx[x] + cy[y] - G[x][y];
if (tmp == 0) // (x, y)在相等子图中
{
visy[y] = true;
if (match[y] == -1 || find(match[y])) // 如果这个点未匹配或者能修改
{
match[y] = x;
return true;
}
}
else if (slack[y] > tmp) // (x, y)不在相等子图中
slack[y] = tmp;
}
return false;
}

void KM()
{
for (int x = 0; x < nx; ++x) // 分别对左端点进行匹配
{
for (int i = 0; i < ny; ++i) // 初始化
slack[i] = inf;
while (true)
{
memset(visx, 0, sizeof(visx)); // 初始化，每次find()更新
memset(visy, 0, sizeof(visy));
if (find(x)) // 成功匹配后换下一个
break;
int delat = inf;
for (int i = 0; i < ny; ++i) // 计算delta值
{
if (!visy[i] && delat > slack[i])
delat = slack[i];
}
for (int i = 0; i < nx; ++i)
{
if (visx[i])
cx[i] -= delat;
}
for (int j = 0; j < ny; ++j)
{
if (visy[j])
cy[j] += delat;
else
slack[j] -= delat;
}
// 修改顶标后，要把所有的slack值都减去delta
// 这是因为lx[i] 减小了delta
// slack[j] = min(lx[i] + ly[j] -w[i][j])
}
}
}

int main()
{
while (scanf("%d", &n) != EOF)
{
ans = 0;
nx = ny = n;
for (int i = 0; i < nx; ++i)
{
for (int j = 0; j < ny; ++j)
scanf("%d", &G[i][j]);
}
for (int i = 0; i < nx; ++i)
{
cx[i] = -inf;
for (int j = 0; j < ny; ++j)
{
if (cx[i] < G[i][j])
cx[i] = G[i][j];
}
}
memset(match, -1, sizeof(match));
memset(cy, 0, sizeof(cy));
KM();
for (int i = 0; i < ny; ++i)
{
if (match[i] != -1)
ans += G[match[i]][i];
}
printf("%d\n", ans);
}
return 0;
}

The end.
2018-05-15 星期二