黑书经典例题,做法与黑书的思想一样,我这里就不多加解释
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int n, m, k;
int g[155][13];
int dp[2][180000];
int cst[11];
int max(int a, int b) { return a > b ? a : b; }
int p1[180000], p2[180000], pt1, pt2;
bool vis[180000];
int f[13];
void go(int zt) { //状态解压成数组
int i;
for(i = 0; i < m; i++) {
f[i] = zt%3;
zt /=3;
}
}
int to(int *a) { // 返回状态
int ret = 0, i;
for(i = m-1; i >= 0; i--)
ret = ret*3 + a[i];
return ret;
}
void dfs(int x, int y, int cnt) {
if(y >= m) {
int zt = to(f);
dp[x&1][zt] = max(dp[x&1][zt], cnt);
if(!vis[zt]) p2[pt2++] = zt;
vis[zt] = 1;
return;
}
int a = f[y];
if(f[y]) f[y]--;
dfs(x, y+1, cnt);
f[y] = a;
if( g[x][y] || g[x-1][y] || g[x][y+1] || g[x-1][y+1]) return;
if( x-1 >= 0 && y+2 < m && !g[x][y+2] && !g[x-1][y+2] ) { // height 2
if(f[y] <= 1 && f[y+1] <= 1 && f[y+2] <= 1) {
int a = f[y], b = f[y+1], c = f[y+2];
f[y] = f[y+1] = f[y+2] = 2;
dfs(x, y+3, cnt+1);
f[y] = a; f[y+1] = b; f[y+2] = c;
}
}
if( x-2 >= 0 && y+1 < m && !g[x-2][y] && !g[x-2][y+1]) { // height 3
if(!f[y] && !f[y+1]) {
f[y] = f[y+1] = 2;
dfs(x, y+2, cnt+1);
f[y] = f[y+1] = 0;
}
}
}
int main() {
int i, j, cas;
cst[0] = 1;
for(i = 1; i <= 11; i++) cst[i] = cst[i-1]*3;
scanf("%d", &cas);
while( ~scanf("%d%d%d", &n, &m, &k)) {
memset(g, 0, sizeof(g));
memset(dp, 0, sizeof(dp));
for(i = 0; i < k; i++) {
int x, y;
scanf("%d%d", &x, &y);
g[--x][--y] = 1;
}
pt2 = 0;
p2[pt2++] = 0;
for(i = 0; i < n-1; i++) {
for(j = 0; j < pt2; j++)
p1[j] = p2[j];
memset(vis, 0, sizeof(vis));
pt1 = pt2; pt2 = 0;
for(j = 0; j < pt1; j++) {
int zt = p1[j];
go(zt);
dfs(i+1, 0, dp[i&1][zt]);
}
}
int ans = 0;
for(i = 0; i < pt2; i++)
ans = max(ans, dp[(n-1)&1][p2[i]]);
printf("%d\n", ans);
}
return 0;
}
/*
100
3 2 0
*/