2020ICPC小米网络赛第二场 A.2020

题目链接

题目描述
Bobo has a string s 1 … s n s_1 \dots s_n s1sn 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

  • 1 ≤ a i < b i < c i < d i ≤ n 1 \leq a_i < b_i < c_i < d_i \leq n 1ai<bi<ci<din
  • s a i s b i s c i s d i = 2020 s_{a_i} s_{b_i} s_{c_i} s_{d_i} = 2020 saisbiscisdi=2020
  • { a i , b i , c i , d i } ∩ { a j , b j , c j , d j } = ∅ \{a_i, b_i, c_i, d_i\} \cap \{a_j, b_j, c_j, d_j\} = \emptyset { ai,bi,ci,di}{ aj,bj,cj,dj}= for i ≠ j i \neq j i=j

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 s1sn.

  • 1 ≤ n ≤ 1 0 5 1 \leq n \leq 10^5 1n105
  • s i ∈ { 0 , 1 , 2 } s_i \in \{0, 1, 2\} si{ 0,1,2}
  • The sum of n does not exceed 1 0 6 10^6 106 .

输出描述:
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;
}

你可能感兴趣的:(二分)