二分/贪心(ICPC小米预赛第一场 A 2020)

题目链接
题意:给你一个只包含0,1,2的序列,问你最多可以同时取出多少个“2020”子序列。
题解:比赛时是队友写出的,赞叹队友的思维能力,真的强。二分答案,然后贪心取即可。检查时传入需要组成x个,遍历数组,每次遇到2,即优先让没有开始组成的序列获取,然后由已经组成到“20”的序列获取。每次遇到0,每次优先由已经组成“2”的序列获取,然后由已经组成“202”的序列获取。最后查看是否组成了x个“2020”
下面是ac代码:

// % everyone
#include <cstdio>
#include<iostream>
#include<cstring>
#include <map>
#include <queue>
#include <set>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <list>
#include <cctype>
#include <time.h>

namespace IO {
    double start_time = 0.0;
    void ct() { start_time = clock(); return; }
    void fast_cin() { std::ios::sync_with_stdio(false); std::cin.tie(); }
    void read_f(int flag = 0) { freopen("0.in", "r", stdin); if(!flag) freopen("0.out", "w", stdout); }
    void run_time() { std::cout << "\nESC in : " << ( clock() - start_time ) * 1000.0 / CLOCKS_PER_SEC << "ms" << std::endl; }
}
using namespace IO;
template <typename T>
bool bacmp(const T & a, const T & b) { return a > b; }
template <typename T>
bool pecmp(const T & a, const T & b) { return a < b; }

#define ll long long
#define ull unsigned ll
#define _min(x, y) ((x)>(y)?(y):(x))
#define _max(x, y) ((x)>(y)?(x):(y))
#define max3(x, y, z) ( max( (x), max( (y), (z) ) ) )
#define min3(x, y, z) ( min( (x), min( (y), (z) ) ) )
#define pr make_pair
#define pb push_back
using namespace std;

const int N = 1e6+5;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;

char su[N];
int dp[6];
int n;
bool che(int x)
{
    memset(dp, 0, sizeof(dp)); dp[0] = x;
    for (int i = 1; i <= n; i++)
    {
        if (su[i] == '2')
        {
            if (dp[0]) dp[0]--,dp[1]++;
            else if (dp[2]) dp[2]--,dp[3]++;
        }
        else if (su[i] == '0')
        {
            if (dp[1]) dp[1]--,dp[2]++;
            else if (dp[3]) dp[3]--,dp[4]++;
        }
    }
    return dp[4]==x;
}
int main()
{

    while(scanf("%d", &n) != EOF)
    {
        scanf("%s", su+1);
        int n = strlen(su+1);
        int l = 0, r = n;
        while(l <= r)
        {
            int mid = (l + r) >> 1;
            if (che(mid)) l = mid+1;
            else r = mid-1;
        }
        printf("%d\n", l-1);
    }
}

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页