POJ 2226. Muddy Fields

链接

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

题意

在一块 $n*m$ 的地面上,有一些格子是泥泞的,有一些格子是长草的。

现在需要用一些宽度为 $1$ 长度任意的木板把泥地盖住,同时不能盖住长草的地面,木板可以重叠,求最少需要多少块木板?

思路

每块泥地要么被横木板覆盖要么被竖木板覆盖。

将横木板作为二分图左边节点,竖木板作为二分图右边节点,对每块泥地所在横木板和竖木板连线。

求出二分图的最小覆盖,就是用最少的木板覆盖所有的泥地。

代码

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <climits>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <bitset>
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(),(x).end()
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define FI first
#define SE second
using namespace std;
typedef double DB;
typedef long long LL;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector<PII> VPII;
//head
const int N=55;
const int M=1300;
char s[N][N];
int n,m,t1,t2,a[M][M],b[M][M],match[M];
bool vis[M][M],st[M];
bool dfs(int u) {
for(int v=1;v<=t2;v++) {
if(!vis[u][v]||st[v]) continue;
st[v]=true;
if(match[v]==-1||dfs(match[v])) {
match[v]=u;
return true;
}
}
return false;
}
int main() {
//freopen("D:/Sublime Text 3/in.txt","r",stdin);
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) scanf("%s",s[i]);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(s[i][j]=='*') {
if(j==0||s[i][j-1]=='.') t1++;
a[i][j]=t1;
}
for(int j=0;j<m;j++)
for(int i=0;i<n;i++)
if(s[i][j]=='*') {
if(i==0||s[i-1][j]=='.') t2++;
b[i][j]=t2;
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(s[i][j]=='*')
vis[a[i][j]][b[i][j]]=true;
int res=0;
for(int i=1;i<=t2;i++) match[i]=-1;
for(int i=1;i<=t1;i++) {
for(int j=1;j<=t2;j++) st[j]=false;
if(dfs(i)) res++;
}
printf("%d\n",res);
return 0;
}