http://poj.org/problem?id=2226
题目大意:
一个农场为R × C的矩阵,其中 * 号的地方为泥巴地;现在要用宽度为1,长度不限的模板覆盖住所有的泥巴地,且不能覆盖到草地,问最小要几块;
思路:
看题目很自然的想到二分图的行列匹配法,这题只是稍微加点处理就行;
把同一行或者同一列的泥巴地看成是一个点,用行列匹配法求解最大匹配就是答案;
#include<iostream>
using namespace std;
int graph[550][550];
int link[550];
bool visit[550];
int vx,vy;
char map[55][55];
int node_x[550][550];
int node_y[550][550];
bool dfs(int x)
{
for(int y=1;y<=vy;y++)
{
if(graph[x][y] && !visit[y])
{
visit[y]=true;
if(link[y]==-1 || dfs(link[y]))
{
link[y]=x;
return true;
}
}
}
return false;
}
int hungary()
{
int max_match=0;
memset(link,-1,sizeof(link));
for(int i=1;i<=vx;i++)
{
memset(visit,false,sizeof(visit));
if(dfs(i))
max_match++;
}
return max_match;
}
int main(int i,int j)
{
int r,c;
while(~scanf("%d%d",&r,&c))
{
/*Input*/
getchar();
for(i=1;i<=r;i++)
{
for(j=1;j<=c;j++)
scanf("%c",&map[i][j]);
getchar();
}
memset(graph,0,sizeof(graph));
/*Structure Graph*/
vx=0;
for(i=1;i<=r;i++)
{
for(j=1;j<=c;j++)
{
if(map[i][j]=='*')
{
if(map[i][j-1]=='*')
node_x[i][j]=node_x[i][j-1];
else
node_x[i][j]=++vx;
}
}
}
vy=0;
for(i=1;i<=r;i++)
{
for(j=1;j<=c;j++)
{
if(map[i][j]=='*')
{
if(map[i-1][j]=='*')
node_y[i][j]=node_y[i-1][j];
else
node_y[i][j]=++vy;
graph[ node_x[i][j] ][ node_y[i][j] ]=1;
}
}
}
/*Hungary Algorithm & Output*/
printf("%d\n",hungary());
}
return 0;
}