-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path604C. Alternative Thinking.cpp
55 lines (45 loc) · 1.18 KB
/
604C. Alternative Thinking.cpp
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
/*
Idea:
- We can solve this problem using Dynamic Programming.
- The state is the index, have I flip a substring or not?, am I still
flipping? and the last character.
*/
#include <bits/stdc++.h>
using namespace std;
int const N = 1e5 + 1;
int n, dp[N][2][2][3];
string s;
int rec(int idx, bool tak, bool til, int lst) {
if(idx == n)
return 0;
int &ret = dp[idx][tak][til][lst];
if(ret != -1)
return ret;
ret = rec(idx + 1, tak, til, lst);
if(!tak) {
if(s[idx] - '0' != lst)
ret = max(ret, rec(idx + 1, tak, til, s[idx] - '0') + 1);
if(s[idx] - '0' == lst)
ret = max(ret, rec(idx + 1, true, true, !(s[idx] - '0')) + 1);
} else {
if(!til) {
if(s[idx] - '0' != lst)
ret = max(ret, rec(idx + 1, tak, til, s[idx] - '0') + 1);
} else {
if(s[idx] - '0' != lst)
ret = max(ret, rec(idx + 1, tak, false, s[idx] - '0') + 1);
if(s[idx] - '0' == lst)
ret = max(ret, rec(idx + 1, tak, til, !(s[idx] - '0')) + 1);
}
}
return ret;
}
int main() {
cin >> n >> s;
memset(dp, -1, sizeof dp);
int res = 0;
for(int i = 0; i < n; ++i)
res = max(res, rec(i, 0, 0, 2));
cout << res << endl;
return 0;
}