题解
经典的状压dp
code
#include<bits/stdc++.h>
#define ll long long
#define lowbit(x) ((x)&(-x))
using namespace std;
int sit[105];
int dp[505][505][4];
bool check(int x)
{
int x1=(x>>1)>>1;
int x2=(x<<1)<<1;
int x3=(x<<1);
int x4=(x>>1);
if((x1&x)||(x2&x)||(x3&x)||(x4&x)) return 0;
else return 1;
}
int cal(int x)
{
int cnt=0;
while(x)
{
x-=lowbit(x);
cnt++;
}
return cnt;
}
void solve()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
string s;
cin>>s;
for(int j=0;s[j];j++)
{
sit[i]<<=1;
sit[i]|=(s[j]=='H'?1:0);
}
}
vector<int> line,sum;
for(int i=0;i<=(1<<m)-1;i++)
{
if(check(i))
{
line.push_back(i);
sum.push_back(cal(i));
}
}
int ans=0;
for(int i=0;i<line.size();i++)
{
if((sit[1]&line[i])==0)
{
dp[i][0][1]=sum[i];
ans=max(ans,dp[i][0][1]);
//printf("1 : down:%d mid:0 up:0 num:%d\n",line[i],sum[i]);
}
}
if(n==1)
{
cout<<ans;
return;
}
for(int i=0;i<line.size();i++)
{
for(int j=0;j<line.size();j++)
{
if((sit[2]&line[j])==0&&(line[j]&line[i])==0&&(line[i]&sit[1])==0)
{
dp[j][i][2]=dp[i][0][1]+sum[j];
ans=max(ans,dp[j][i][2]);
//printf("2 : down:%d mid:%d up:0 num:%d\n",line[j],line[i],sum[i]+sum[j]);
}
}
}
if(n==2)
{
cout<<ans;
return;
}
for(int i=3;i<=n;i++)
{
for(int j=0;j<line.size();j++)
{
if(line[j]&sit[i]) continue;
for(int k=0;k<line.size();k++)
{
if(line[k]&sit[i-1]) continue;
if(line[k]&line[j]) continue;
for(int l=0;l<line.size();l++)
{
if(line[l]&sit[i-2]) continue;
if(line[l]&line[k]) continue;
if(line[l]&line[j]) continue;
dp[j][k][i%3]=max(dp[j][k][i%3],dp[k][l][(i-1)%3]+sum[j]);
ans=max(ans,dp[j][k][i%3]);
// printf("%d : down:%d mid:%d up:0 num:%d\n",i,line[i],line[j],line[k],dp[j][k][i%3]);
}
}
}
}
cout<<ans;
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t=1;
//cin>>t;
while(t--) solve();
return 0;
}
标签:cnt,return,sit,int,炮兵阵地,long,NOI2001,P2704
From: https://www.cnblogs.com/pure4knowledge/p/18314974