题目
题目链接:http://poj.org/problem?id=2226
题目来源:http://www.cnblogs.com/vongang/archive/2012/02/21/2361882.html
题解
若没有限制dot不能覆盖,则直接按照横和纵坐标建二分图跑最大匹配转最小点覆盖。
限制了dot无法覆盖则需要从当中截断,把横向和纵向连续的*给缩点,建二分图跑最大匹配即可。
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
// head
const int N = 1005;
const int M = N;
const int E = N * N;
struct Gragh {
struct Edge {
int to, nxt;
Edge(int to, int nxt) : to(to), nxt(nxt) {}
Edge() {}
};
Edge e[E];
int head[N], match[M], ec;
bool vis[N];
void addEdge(int from, int to) {
e[ec] = Edge(to, head[from]);
head[from] = ec++;
}
void init(int n, int m) {
ec = 0;
for (int i = 0; i <= n; i++) head[i] = -1;
for (int i = 0; i <= m; i++) match[i] = -1;
}
bool dfs(int x) {
vis[x] = true;
for (int i = head[x]; ~i; i = e[i].nxt) {
int to = e[i].to, w = match[to];
if (w == -1 || (!vis[w] && dfs(w))) {
match[to] = x;
return true;
}
}
return false;
}
int bipatiteMatch(int n) {
int ans = 0;
for (int i = 0; i < n; i++) {
memset(vis, 0, sizeof vis);
if (dfs(i)) ans++;
}
return ans;
}
};
Gragh g;
char s[N][N];
int r[N][N];
int c[N][N];
int main() {
int n, m;
while (scanf("%d%d", &n, &m) == 2) {
for (int i = 0; i < n; i++) {
scanf("%s", s[i]);
}
int rc = 0;
for (int i = 0; i < n; i++) {
int cur = 0;
while (cur < m) {
while (cur < m && s[i][cur] == '.') cur++;
while (cur < m && s[i][cur] == '*') r[i][cur++] = rc;
if (s[i][cur-1] == '*') rc++;
}
}
int cc = 0;
for (int j = 0; j < m; j++) {
int cur = 0;
while (cur < n) {
while (cur < n && s[cur][j] == '.') cur++;
while (cur < n && s[cur][j] == '*') c[cur++][j] = cc;
if (s[cur-1][j] == '*') cc++;
}
}
g.init(rc, cc);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (s[i][j] == '*') g.addEdge(r[i][j], c[i][j]);
}
}
printf("%d\n", g.bipatiteMatch(rc));
}
return 0;
}