稍后放出解释。。。
int st[66];
int cur[66];
char str[110][15];
int dp[110][66][66];//dp[i][j][k] 表示第i行状态为j,第i-1状态为k时的最大炮兵个数
int num[66];
int n,m;
int tot;
bool ok(int x){
if(x & (x<<1))return 0;
if(x & (x<<2))return 0;
return 1;
}
void init(){
int i,j;
tot = 0;
for(i=0;i<(1<<m);i++){
if(ok(i))st[tot++] = i;
}
}
int count(int x){
int cnt = 0 ;
while(x){
if(x&1)cnt++;
x>>=1;
}
return cnt;
}
bool fit(int x,int y){
if(x&y)return 0;
return 1;
}
int main(){
while(scanf("%d%d",&n,&m) != -1){
int i,j,k;
init();
for(i=0;i<n;i++){
scanf("%s",str[i]);
cur[i] = 0;
for(j=0;j<m;j++){
if(str[i][j]=='H'){
cur[i] += (1<<j);
}
}
}
memset(dp,-1,sizeof(dp));
for(i=0;i<tot;i++){
num[i] = count(st[i]);
if(fit(st[i],cur[0])){
dp[0][i][0] = num[i];
}
}
for(int r = 1;r<n;r++){
for(i=0;i<tot;i++){
if(!fit(cur[r],st[i]))continue;
for(j=0;j<tot;j++){
if(st[i]&st[j])continue;
for(k=0;k<tot;k++){
if(st[i]&st[k])continue;
if(dp[r-1][j][k]!=-1){
dp[r][i][j] = max(dp[r][i][j],dp[r-1][j][k]+num[i]);
}
}
}
}
}
int ans = 0;
for(i=0;i<tot;i++){
for(j=0;j<tot;j++){
ans = max(ans,dp[n-1][i][j]);
}
}
printf("%d\n",ans);
}
return 0;
}

本文探讨了一种解决最大炮兵排列优化问题的算法,通过动态规划和位运算技巧,实现高效求解。
1433

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



