题目链接http://poj.org/problem?id=3020
*--代表城市,o--代表空地
给城市安装无线网,一个无线网最多可以覆盖两座城市,问覆盖所有城市最少要用多少无线。
公式:,最小路径覆盖=总节点数-最大匹配数;
那么接下来需要确认的是,
究竟是求 有向二分图的最小路覆盖,还是求 无向二分图的最小路覆盖
因为有向和无向是截然不同的计算方法。
例如输入:
*oo
***
O*o
时,可以抽象为一个数字地图:
100
234
050
即任意两个城市(顶点)之间的边是成对出现的
那么我们就可以确定下来,应该 构造无向二分图(其实无向=双向)
无向二分图的最小路径覆盖 = 顶点数 – 最大二分匹配数/2
接下来就是套模板了
#include<cstdio>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#define ll long long
using namespace std;
const int maxn=405;
const int maxm=405*405*2;
char mp[450][450];
int p[maxn][maxn];
int next[4][2]={1,0,0,1,0,-1,-1,0};
struct Edge
{
int to,next;
}edge[maxm];
int head[maxn],tot;
void init()
{
tot=0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
}
int linker[maxn];
bool used[maxn];
int un;
bool dfs(int u)
{
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(!used[v])
{
used[v]=true;
if(linker[v]==-1||dfs(linker[v]))
{
linker[v]=u;
return true;
}
}
}
return false;
}
int hungary()
{
int res=0;
memset(linker,-1,sizeof(linker));
for(int u=1;u<=un;u++)
{
memset(used,false,sizeof(used));
if(dfs(u))res++;//cout<<res<<endl;
}
return res;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
init();
memset(p,0,sizeof(p));
int n,m;
char c;
int cnt=0;
scanf("%d%d",&n,&m);
getchar();
for(int i=0;i<n;i++)
{
gets(mp[i]);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mp[i][j]=='*')
{
p[i][j]=++cnt;
}
}
}
un=cnt;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(p[i][j]){
for(int k=0;k<4;k++)
{
int xx=i+next[k][0];
int yy=j+next[k][1];
if(xx<0||xx>=n||yy<0||yy>=m)
continue;
if(p[xx][yy])
{
addedge(p[i][j],p[xx][yy]);
//cout<<p[i][j]<<" "<<p[xx][yy]<<endl;
}
}
}
}
}
printf("%d\n",cnt-hungary()/2);
}
}