链接:
https://www.nowcoder.com/acm/contest/119/J
来源:牛客网
来源:牛客网
题目描述
It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
There is an N×M grid, some are black and some are white. You can choose some grids that are black initially, and change the color of these grids and their adjacent grids to white at the same time. You have to figure out the minimum grids you need to choose to change the color of all grids into white.
There is an N×M grid, some are black and some are white. You can choose some grids that are black initially, and change the color of these grids and their adjacent grids to white at the same time. You have to figure out the minimum grids you need to choose to change the color of all grids into white.
输入描述:
There are two integers N and M(N+M≤25) in the first line, as described above. Then there is an N×M grid followed, indicating the color of each grid. ‘#’ denotes black grid and ‘.’denotes white grid.
输出描述:
Output the minimum grids you need to choose.
题解:
与数独问题类似,每个#建立一行,所在位置建为1,
若有#与之相邻,则在这一行相应的位置也置为1,即
转化为求精确覆盖问题。注意这里当去掉其中一行时
并不能把矛盾的几行 都去掉,而是把矛盾的行中
矛盾的元素去掉。然后A*搜索优化一下。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxnode=100100;
char t[33][33];
int a[33][33];
int d[5][2]={{-1,0},{0,-1},{0,0},{0,1},{1,0}};
struct node
{
int n,m,ansd,len;
int U[maxnode],D[maxnode],L[maxnode],R[maxnode];
int col[maxnode],row[maxnode];
int H[maxnode],S[maxnode];
void init(int _n,int _m)
{
n=_n,m=_m;
for(int i=0;i<=m;i++)
{
U[i]=D[i]=i;
R[i]=i+1;
L[i]=i-1;
S[i]=0;
}
R[m]=0;L[0]=m;
ansd=1e9;
for(int i=1;i<=n;i++)
H[i]=-1;
len=m;
}
void Link(int r,int c)
{
D[++len]=D[c];
U[D[c]]=len;
U[len]=c;
D[c]=len;
row[len]=r;
col[len]=c;
S[c]++;
if(H[r]<0)
H[r]=L[len]=R[len]=len;
else
{
R[len]=R[H[r]];
L[R[H[r]]]=len;
L[len]=H[r];
R[H[r]]=len;
}
}
void remove(int c)
{
for(int i=D[c];i!=c;i=D[i])
{
L[R[i]]=L[i];
R[L[i]]=R[i];
}
}
void resume(int c)
{
for(int i=U[c];i!=c;i=U[i])
{
L[R[i]]=i;
R[L[i]]=i;
}
}
bool v[maxnode];
int f()
{
for(int i=R[0];i!=0;i=R[i])
{
v[i]=1;
}
int ans=0;
for(int i=R[0];i!=0;i=R[i])
{
if(v[i])
{
ans++;
v[i]=0;
for(int j=D[i];j!=i;j=D[j])
{
for(int k=R[j];k!=j;k=R[k])
v[col[k]]=0;
}
}
}
return ans;
}
void Dance(int d)
{
if(d+f()>=ansd)return;
if(R[0]==0)
{
ansd=min(ansd,d);
return;
}
int c=R[0];
for(int i=R[0];i!=0;i=R[i])
if(S[i]<S[c])
c=i;
for(int i=D[c];i!=c;i=D[i])
{
remove(i);
for(int j=R[i];j!=i;j=R[j])
remove(j);
Dance(d+1);
for(int j=L[i];j!=i;j=L[j])
resume(j);
resume(i);
}
}
}g;
int main()
{
int n,m;scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%s",&t[i]);
int k=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(t[i][j]=='#')
a[i][j]=++k;
}
}
g.init(k,k);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(t[i][j]=='#')
{
for(k=0;k<5;k++)
{
int x=i+d[k][0],y=j+d[k][1];
if(x>=0&&x<n&&y>=0&&y<m&&t[x][y]=='#')
{
g.Link(a[i][j],a[x][y]);
}
}
}
}
}
g.Dance(0);
printf("%d\n",g.ansd);
return 0;
}

本文介绍了一种将黑白网格问题转化为精确覆盖问题的方法,并通过A*搜索进行优化。利用图论和算法技巧解决如何最少操作使所有格子变白的问题。

被折叠的 条评论
为什么被折叠?



