本题与poj3254差不多,所以分析手法不多讲,直接看代码
#include<iostream>
using namespace std;
int f[105][62][62],b[1050];
bool a[105][12];
int i,j,k,t,l,m,n,tot=0,ans;
int isok(int row,int x,int y,int z)
{
int i,ans=0;
x=b[x];
y=b[y];
z=b[z];
for(i=0;i<m;i++)
if(z>>i&1)
{
if(!a[row][i]||x>>i&1||y>>i&1)
return -1;
ans++;
}
return ans;
}
int main()
{
cin>>n>>m;
getchar();
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
a[i][j]=(getchar()=='P');
getchar();
}
for(i=0;i<(1<<m);i++)
{
int v[12]={0};
for(j=0;j<m;j++)
if((i>>j)&1)
for((j-2>=0)?k=j-2:k=0;k<=j+2&&k<m;k++)
v[k]++;
bool ok=1;
for(j=0;j<m;j++)
if(i>>j&1&&v[j]>1)
ok=0;
if(!ok)
continue;
b[++tot]=i;
}
for(i=0;i<=n;i++)
for(j=1;j<=tot;j++)
for(k=1;k<=tot;k++)
f[i][j][k]=-1;
f[0][1][1]=0;
for(i=0;i<n;i++)
for(j=1;j<=tot;j++)
for(k=1;k<=tot;k++)
if(f[i][j][k]!=-1)
for(l=1;l<=tot;l++)
{
t=isok(i,j,k,l);
if(t>=0&&f[i][j][k]+t>f[i+1][k][l])
f[i+1][k][l]=t+f[i][j][k];
}
ans=0;
for(i=1;i<=tot;i++)
for(j=1;j<=tot;j++)
if(f[n][i][j]>ans)
ans=f[n][i][j];
cout<<ans;
return 0;
}