您的位置:首页 > 其它

poj2226 二分图匹配经典行列建图

2016-04-30 17:00 274 查看
http://poj.org/problem?id=2226

题目大意:

如何放木板保证只覆盖到’*’ 而没有覆盖到’.’。

思路:

进行行列建图,将横着的木板作为二分图中一侧的点,竖着的木板作为另一侧,定义出二分图。对于每一个’*’的点,考虑横着的木板如何覆盖它,竖着的如何覆盖,如何定义横着覆盖它的木板的编号,其实就可以把每一个需要覆盖的顶点所在的泥地上的最左端的顶点作为横着木板的编号,所在泥地最上端的顶点作为竖着的,将最左端的顶点和最上端的顶点连边建立二分图。最后求最小的顶点覆盖。就是等于保证每个泥地都被横着的木板或者竖着的木板覆盖了。

代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
#define M 10009
vector<int> G[M];
char mp[M][M];
bool used[M];
int match[M];
int n,m;
void init()
{
for(int i = 0;i <= 2*n*m;i++) G[i].clear();
}
void add_edge(int u,int v)
{
G[u].push_back(v);
G[v].push_back(u);
}
bool dfs(int u)
{
for(int i = 0;i < G[u].size();i++)
{
int v = G[u][i];
if(!used[v])
{
used[v] = true;
if(match[v] < 0 || dfs(match[v]))
{
match[v] = u;
return true;
}
}
}
return false;
}
int hungry()
{
int res = 0;
memset(match,-1,sizeof(match));
for(int i = 0;i < n*m;i++)
{
memset(used,false,sizeof(used));
if(dfs(i)) res++;
}
return res;
}
int main()
{
while(scanf("%d %d",&n,&m) == 2)
{
for(int i = 0;i < n;i++)
{
scanf("%s",mp[i]);
}
for(int i = 0; i < n;i++)
{
for(int j = 0;j < m;j++)
{
if(mp[i][j] == '*')
{
int x = i,y = j;
while(x > 0 && mp[x-1][j] == '*') x--;
while(y > 0 && mp[i][y-1] == '*') y--;
add_edge(x*m+j,i*m+y+m*n);
}
}
}
printf("%d\n",hungry());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: