题目传送门
1 /*
2 题意:给一个串,只能是0,1,?(0/1)。计算格雷码方法:当前值与前一个值异或,若为1,可以累加a[i],问最大累加值
3 DP:dp[i][0/1]表示当前第i位选择0/1时的最大分数,那么分类讨论,情况太多,看代码,注意不可能的状态不要转移
4 */
5 /************************************************
6 * Author :Running_Time
7 * Created Time :2015-8-11 15:49:03
8 * File Name :G.cpp
9 ************************************************/
10
11 #include <cstdio>
12 #include <algorithm>
13 #include <iostream>
14 #include <sstream>
15 #include <cstring>
16 #include <cmath>
17 #include <string>
18 #include <vector>
19 #include <queue>
20 #include <deque>
21 #include <stack>
22 #include <list>
23 #include <map>
24 #include <set>
25 #include <bitset>
26 #include <cstdlib>
27 #include <ctime>
28 using namespace std;
29
30 #define lson l, mid, rt << 1
31 #define rson mid + 1, r, rt << 1 | 1
32 typedef long long ll;
33 const int MAXN = 2e5 + 10;
34 const int INF = 0x3f3f3f3f;
35 const int MOD = 1e9 + 7;
36 char s[MAXN];
37 int a[MAXN];
38 int dp[MAXN][2];
39
40 int work(int n) {
41 memset (dp, 0, sizeof (dp));
42 if (s[1] == '?') dp[1][1] = a[1];
43 else {
44 int t = s[1] - '0';
45 if (t == 1) dp[1][1] = a[1];
46 }
47 for (int i=2; i<=n; ++i) {
48 if (s[i] == '?') {
49 if (s[i-1] == '?') {
50 dp[i][0] = max (dp[i-1][0], dp[i-1][1] + a[i]);
51 dp[i][1] = max (dp[i-1][1], dp[i-1][0] + a[i]);
52 }
53 else {
54 int t = s[i-1] - '0';
55 dp[i][1-t] = max (dp[i-1][1-t], dp[i-1][t] + a[i]);
56 dp[i][t] = dp[i-1][t];
57 }
58 }
59 else {
60 if (s[i-1] == '?') {
61 int t = s[i] - '0';
62 dp[i][t] = max (dp[i-1][t], dp[i-1][1-t] + a[i]);
63 }
64 else {
65 int tt = s[i-1] - '0', t = s[i] - '0';
66 dp[i][t] = dp[i-1][tt] + ((tt != t) ? a[i] : 0);
67 }
68 }
69 }
70
71 if (s[n] == '?') {
72 return max (dp[n][0], dp[n][1]);
73 }
74 else return dp[n][s[n]-'0'];
75 }
76
77 int main(void) { //HDOJ 5375 Gray code
78 int T, cas = 0; scanf ("%d", &T);
79 while (T--) {
80 scanf ("%s", s + 1);
81 int len = strlen (s + 1);
82 for (int i=1; i<=len; ++i) scanf ("%d", &a[i]);
83 printf ("Case #%d: %d
", ++cas, work (len));
84 }
85
86 return 0;
87 }