版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/changingseasons/article/details/53045810
题意:有一片n*m的海,其中有冰山、浮冰和海水,现在向海里放战舰,战舰只能放在海水里,并且每一行每一列只能放一艘战舰,除非两艘战舰之间有冰山相隔,问最多能放多少艘战舰。
分析:很明显二分图匹配,把海水分成横着的块和竖着的块,每一块海水没有冰山相隔,所以一块只能放一艘战舰,当横着的块和竖着的块有相同的点时,就连接一条边,然后求最大匹配数目。
细节参见代码:
#include<iostream>
#include<cstdio>
#include<map>
#include<vector>
#include<string>
#include<cstring>
using namespace std;
int t,n,m,cnt;
char str[55][55];
int x[55][55],y[55][55];
vector<int> g[50*50+5];
int from[50*50+5],tot;
bool used[50*50+5];
bool match(int x)
{
for(int i=0; i<g[x].size(); i++)
if(!used[g[x][i]])
{
used[g[x][i]]=true;
if(from[g[x][i]]==-1||match(from[g[x][i]]))
{
from[g[x][i]]=x;
return true;
}
}
return false;
}
int hungary()
{
tot=0;
memset(from,-1,sizeof from);
for(int i=1; i<=cnt; i++)
{
memset(used,0,sizeof used);
if(match(i))
{
++tot;
}
}
}
void getx()
{
int x1=1;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
if(str[i][j]=='*') x[i][j]=x1;
if(str[i][j]=='#') x1++;
}
x1++;
}
cnt=x1;
}
int gety()
{
int y1=1;
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
if(str[j][i]=='*') y[j][i]=y1;
if(str[j][i]=='#') y1++;
}
y1++;
}
cnt=max(cnt,y1);
}
int main()
{
scanf("%d",&t);
while(t--)
{
cnt=0;
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
memset(str,0,sizeof(str));
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++) scanf("%s",str[i]+1);
getx();
gety();
for(int i=0;i<=n*m+1;i++) g[i].clear();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(str[i][j]=='*') g[x[i][j]].push_back(y[i][j]);
hungary();
printf("%d\n",tot);
}
return 0;
}