zoj 3802 Easy 2048 Again

本文从WordPress迁移而来, 查看全部WordPress迁移文章

状态压缩DP

最重要的一点,保证后缀是递减

时限很紧,先预处理出所有的转移和新增的收益,dp的时候就能O(1)转移了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <utility>
using namespace std;
#define pii pair<int,int>
#define mp make_pair
#define MAXSTATUS (1<<12)
#define MAXN 510

int dp[MAXN][MAXSTATUS];
int mats[MAXSTATUS][17];
int matc[MAXSTATUS][17];
int n,a[MAXN];

inline void cal(int s,int num) {
if (s == 0) {
mats[s][num] = num>>1;
matc[s][num] = num;
return ;
}
int &news = mats[s][num];
int &sum = matc[s][num];
sum = num;
for (int i = 0; i < 12; i++) if (s&(1<<i)) {
if ((1<<i) == (num>>1)) {
news = num;
sum += (num<<1);
num <<= 1;
}
else if ((1<<i) < (num>>1)) {
news = (num>>1);
return;
}
else {
if (news == 0) news = (num>>1);
for (int j = i; j < 12; j++) {
if (s&(1<<j)) news += (1<<j);
}
return;
}
}
}

void init() {
memset(mats, 0, sizeof(mats));
memset(matc, 0, sizeof(matc));
int maxstatus = MAXSTATUS;
for (int s = 0; s < maxstatus; s++) {
for (int i = 1; i < 5; i++) {
cal(s, (1<<i));
}
}
}

int DP() {
int maxstatus = MAXSTATUS;
memset(dp, -1, sizeof(dp));
dp[0][0] = 0;
for (int ith = 0; ith < n; ith++) {
for (int status = 0; status < maxstatus; status++) {
if (dp[ith][status] == -1) continue;
int news = mats[status][a[ith+1]];
int cost = matc[status][a[ith+1]];
int dp1 = dp[ith][status];
int &dp2 = dp[ith+1][status];
int &dp3 = dp[ith+1][news];
dp2 = max(dp2, dp1);
dp3 = max(dp3, dp1 + cost);
}
}
int ans = 0;
for (int status = 0; status < maxstatus; status++) {
ans = max(ans, dp[n][status]);
}
return ans;
}

int main() {
init();
int CASE;
scanf("%d", &CASE);
while (CASE--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
printf("%d\n", DP());
}
return 0;
}