题目链接
题目描述
Bobo has a string s 1 … s n s_1 \dots s_n s1…sn of length n n n consisting of only digits 0 , 1 0, 1 0,1, and 2 2 2, and he wants to pick some disjoint subsequences which equal to 2020 2020 2020, as many as possible.
Formally, Bobo would like to find k k k quadrangle ( a 1 , b 1 , c 1 , d 1 ) , … , ( a k , b k , c k , d k ) (a_1, b_1, c_1, d_1), \dots, (a_k, b_k, c_k, d_k) (a1,b1,c1,d1),…,(ak,bk,ck,dk) where
Find the maximum value of k k k.
输入描述:
The input consists of several test cases terminated by end-of-file.
The first line of each test case contains an integer n and the second line contains a string s 1 … s n s_1 \dots s_n s1…sn.
输出描述:
For each test case, print an integer which denotes the result.
示例1
输入
4
2222
7
2101210
8
22002200
输出
0
1
2
二分答案即可
#include
using namespace std;
const int N = 1e5 + 10;
int cnt[4], n;
char a[N];
inline bool check(int x) {
memset(cnt, 0, sizeof(cnt));
cnt[0] = x;
for (int i = 1; i <= n; ++i) {
if (a[i] == '2') {
if (cnt[0])cnt[0]--, cnt[1]++;
else if (cnt[2])cnt[2]--, cnt[3]++;
} else if (a[i] == '0') {
if (cnt[1])cnt[1]--, cnt[2]++;
else if (cnt[3])cnt[3]--;
}
}
if (cnt[0] || cnt[1] || cnt[2] || cnt[3])return false;
return true;
}
int main() {
while (~scanf("%d", &n)) {
scanf("%s", a + 1);
int l = 0, r = n >> 2;
while (l < r) {
int mid = (l + r + 1) >> 1;
check(mid) ? (l = mid) : (r = mid - 1);
}
printf("%d\n", l);
}
return 0;
}