Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8881 | Accepted: 3300 |
Description
To prevent those muddy hooves, Farmer John will place a number of wooden boards over the muddy parts of the cows' field. Each of the boards is 1 unit wide, and can be any length long. Each board must be aligned parallel to one of the sides of the field.
Farmer John wishes to minimize the number of boards needed to cover the muddy spots, some of which might require more than one board to cover. The boards may not cover any grass and deprive the cows of grazing area but they can overlap each other.
Compute the minimum number of boards FJ requires to cover all the mud in the field.
Input
* Lines 2..R+1: Each line contains a string of C characters, with '*' representing a muddy patch, and '.' representing a grassy patch. No spaces are present.
Output
Sample Input
4 4
*.*.
.***
***.
..*.
Sample Output
4
Hint
Boards 1, 2, 3 and 4 are placed as follows:
1.2.
.333
444.
..2.
Board 2 overlaps boards 3 and 4.
Source
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
#include <set>
using namespace std; #define N 50 int max(int x,int y){return x>y?x:y;}
int min(int x,int y){return x<y?x:y;}
int abs(int x,int y){return x<?-x:x;} int n, m;
vector<int>ve[N*N];
int from[N*N];
bool visited[N*N];
char map[N][N];
int map1[N][N];
int map2[N][N]; int march(int u){
int i, v;
for(i=;i<ve[u].size();i++){
v=ve[u][i];
if(!visited[v]){
visited[v]=true;
if(from[v]==-||march(from[v])){
from[v]=u;
return ;
}
}
}
return ;
} main()
{
int i, j, k;
while(scanf("%d %d",&n,&m)==){
for(i=;i<n;i++) scanf("%s",map[i]);
memset(map1,-,sizeof(map1));
memset(map2,-,sizeof(map2));
int num=;
int maxh=;
//横着处理
for(i=;i<n;i++){
for(j=;j<m;j++){
if(map[i][j]=='*'){
if(j==) map1[i][j]=num;
else{
if(map[i][j-]=='*') map1[i][j]=map1[i][j-];
else map1[i][j]=num;
}
}
else {
if(j<m-&&map[i][j+]=='*') num++;
}
}
num++;
maxh=max(maxh,num);
}
//竖着处理
num=;
for(j=;j<m;j++){
for(i=;i<n;i++){
if(map[i][j]=='*'){
if(i==) map2[i][j]=num;
else{
if(map[i-][j]=='*') map2[i][j]=map2[i-][j];
else map2[i][j]=num;
}
}
else{
if(i<n-&&map[i+][j]=='*') num++;
}
}
num++;
maxh=max(maxh,num);
}
//建二分图
for(i=;i<maxh;i++) ve[i].clear();
for(i=;i<n;i++){
for(j=;j<m;j++){
if(map1[i][j]!=-&&map2[i][j]!=-){
ve[map1[i][j]].push_back(map2[i][j]);
}
}
}
//二分匹配
memset(from,-,sizeof(from));
num=;
for(i=;i<maxh;i++){
memset(visited,false,sizeof(visited));
if(march(i)) num++;
}
printf("%d\n",num);
}
}