POJ 2226 - Muddy Fields(二分图匹配)

时间:2021-02-07 06:14:58

题目:

http://poj.org/problem?id=2226

题意:

R*C的矩阵,将泥地(*)铺满但不能覆盖草地(.),求出最少的木板段数。

思路:

本题的特别之处是不能覆盖菜地,若一行中的泥地中间有菜地的话则应将泥地分成两点,列的话也同样操作。

AC.

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int maxn = 1000;
int R, C, x, y;
char mp[maxn][maxn];
int g[maxn][maxn], tmp[maxn][maxn], linker[maxn];
bool used[maxn];

bool dfs(int u)
{
for(int v = 0; v < y; ++v) {
if(g[u][v] && !used[v]) {
used[v] = 1;
if(linker[v] == -1 || dfs(linker[v])) {
linker[v] = u;
return 1;
}
}
}
return 0;
}
int hungary()
{
int res = 0;
memset(linker, -1, sizeof(linker));
for(int u = 0; u < x; ++u) {
memset(used, 0, sizeof(used));
if(dfs(u)) res++;
}
return res;
}
int main()
{
//freopen("in", "r", stdin);
while(~scanf("%d %d", &R, &C)) {
memset(g, 0, sizeof(g));
memset(tmp, 0, sizeof(tmp));

for(int i = 0; i < R; ++i) {
scanf("%s", mp[i]);
}
x = 0, y = 0;
for(int i = 0; i < R; ++i) {
int j = 0;
while(j < C) {
while(mp[i][j] == '*' && j < C) {
tmp[i][j++] = x;
}
while(mp[i][j] != '*' && j < C) {
j++;
}
x++;
}
}
for(int j = 0; j < C; ++j) {
int i = 0;
while(i < R) {
while(mp[i][j] == '*' && i < R) {
g[tmp[i][j]][y] = 1;
i++;
}
while(mp[i][j] != '*' && i < R) {
i++;
}
y++;
}
}

int ans = hungary();
printf("%d\n", ans);
}
return 0;
}