# 二维状压DP经典题

## 炮兵阵地

``````#include <bits/stdc++.h>
using namespace std;
int n,m,ans;
int dp[105][65][65];
int num[105],temp[105];
int state[105][65];
int c[1 << 10 + 5];
int count(int x){
int sum = 0;
while(x){
if(x & 1) sum++;
x >>= 1;
}
return sum;
}
int main(){
cin >> n >> m;
//每行的合法状态最多只有60种!
// int p = 0;
// for(int i = 0;i< (1 << 10);i++){
//     int now = i;
//     if((now & (now >> 1)) == 0 && (now & (now >> 2)) == 0) p++;
// }
// cout << p << endl;
for(int i = 1;i <= n;i++){
string s;
cin >> s;
for(int j = 0;j < m;j++){
if(s[j] == 'P') temp[i] += (1 << j);
}
}
//对第0行特殊处理
state[0][++num[0]] = 0;
//预处理合法状态
for(int i = 0;i < (1 << m);i++){
for(int j = 1;j <= n;j++){
int now = i;
if(!(now & (now >> 1)) && !(now & (now >> 2))
&& (now | temp[j]) == temp[j]){
state[j][++num[j]] = i;
c[i] = count(i);
}
}
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= num[i];j++){
int now = state[i][j];
//对第一行特殊处理，防止越界
if(i == 1) {
dp[i][j][1] = max(dp[i][j][1],c[now]);
continue;
}
for(int k = 1;k <= num[i - 1];k++){
int pre = state[i - 1][k];
if(!(now & pre)){
for(int l = 1;l <= num[i - 2];l++){
int pree = state[i - 2][l];
if(!(now & pree) && !(pre & pree)){
dp[i][j][k] = max(dp[i][j][k],dp[i - 1][k][l] + c[now]);
}
}
}
}
}
}
for(int i = 1;i <= num[n];i++){
for(int j = 1;j <= num[n - 1];j++){
ans = max(ans,dp[n][i][j]);
}
}
cout << ans << endl;
return 0;
}``````

## 排兵布阵 HDU4539

``````#include<bits/stdc++.h>
using namespace std;
int n,m,ans;
int state[105],num[170],c[1 << 10 + 5],legal[105][170],dp[105][170][170];
int count1(int x){
int sum = 0;
while(x){
if(x & 1) sum++;
x >>= 1;
}
return sum;
}
bool ok(int now,int row){
return (now & (now >> 2)) == 0 && (now | state[row]) == state[row];
}
bool check(int now,int pre){
return (now & (pre >> 1)) == 0 && (now & (pre << 1)) == 0;
}
bool recheck(int now,int pree){
return (now & pree) == 0;
}
//由于是多组数据，所以每次都要初始化!
void init(){
ans = 0;
memset(num,0,sizeof(num));
memset(dp,0,sizeof(dp));
memset(state,0,sizeof(state));
}
int main()
{
memset(c,-1,sizeof(c));
while(~scanf("%d %d",&n,&m)){
init();
for(int i = 1;i <= n;i++){
for(int j = 0;j < m;j++){
int x;
scanf("%d",&x);
if(x) state[i] |= (1 << j);
}
}
//预处理合法状态
legal[0][++num[0]] = 0;
for(int i = 0;i < (1 << m);i++){
for(int j = 1;j <= n;j++){
if(ok(i,j)) {
legal[j][++num[j]] = i;
if(c[i] == -1) c[i] = count1(i);
}
}
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= num[i];j++){
int s1 = legal[i][j];
if(i == 1) {
dp[i][j][1] = max(dp[i][j][1],c[s1]);
continue;
}
for(int k = 1;k <= num[i - 1];k++){
int s2 = legal[i - 1][k];
if(check(s1,s2)){
for(int l = 1;l <= num[i - 2];l++){
int s3 = legal[i - 2][l];
if(recheck(s1,s3)){
dp[i][j][k] = max(dp[i][j][k],dp[i-1][k][l] + c[s1]);
}
}
}
}
}
}
for(int i = 1;i <= num[n];i++){
for(int j = 1;j <= num[n - 1];j++){
ans = max(ans,dp[n][i][j]);
}
}
printf("%d\n",ans);
}
return 0;
}
``````

(0)
(0)