Loading

CodeForces-1680C Binary String

Binary String

二分 + 尺取 || 尺取

二分+尺取:时间复杂度为 \(O(nlogn)\)

答案是单调的,所以直接二分枚举答案,然后再 judge 判断的时候,尺取中间剩下的区间

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <deque>
#include <stack>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
const ll maxn = 2e5 + 10;
const ll inf = 1e17 + 10;
string s;
int sum = 0;

int query(int x)
{
    int l = 0, r = 0, len = s.length(), cnt0 = 0, cnt1 = 0;
    while(l < len)
    {
        while(r < len && cnt0 <= x)
        {
            if(s[r] == '0') cnt0++;
            else cnt1++;
            r++;
        }
        if(sum - cnt1 <= x) return true;
        if(s[l] == '1') cnt1--;
        else cnt0--;
        l++;
    }
    return max(cnt0, sum - cnt1) <= x;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    while(t--)
    {
        cin >> s;
        int l = 0, r = s.length();
        sum = 0;
        for(int i=0; i<s.length(); i++) if(s[i] == '1') sum++;
        while(l < r)
        {
            int mid = l + r >> 1;
            if(query(mid))
                r = mid;
            else
                l = mid + 1;
        }
        cout << l << endl;
    }

    return 0;
}

尺取,时间复杂度为 \(O(n)\)

这里用到一个贪心,只有在剩余区间的代价和删除区间的代价尽可能相等的时候,是最优解

所以就可以根据这个,尺取每个区间 \([l, r]\),因为对于区间 \([l_{i+1}, r_{i+1}]\),必然有 \(r_i \leq r_{i+1}\)

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    while(t--)
    {
        string s;
        cin >> s;
        int cnt0 = 0, cnt1 = 0, len = s.length();
        for(int i=0; i<len; i++) cnt1 += s[i] == '1';
        int l = 0, r = 0;
        int ans = len;
        while(l < len)
        {
            while(r < len && cnt1 != cnt0)
            {
                if(s[r] == '0') cnt0++;
                else cnt1--;
                r++;
            }
            ans = min(ans, max(cnt0, cnt1));
            if(s[l] == '0') cnt0--;
            else cnt1++;
            l++;
        }
        cout << ans << endl;
    }
    return 0;
}
posted @ 2022-05-14 15:40  dgsvygd  阅读(175)  评论(0编辑  收藏  举报