1 条题解

  • 0
    @ 2025-8-11 15:15:46

    O(N)O(N)

    严格交替的字符串只有两种情况:

    1. 以0开头(0101...)

    2. 以1开头(1010...)

    对于每种情况,计算当前字符串与目标不同的位置数量。这些不同的位置需要被修正.

    每次反转操作可以修正连续的差异段。最优策略是每次操作处理尽可能多的连续差异。

    #include<bits/stdc++.h>
    
    using namespace std;
    
    typedef long long LL;
    typedef pair<LL, LL> PII;
    
    #define x first
    #define y second
    
    const int N = 2e5 + 10, M = 30;
    
    int cmp(string s, string t)
    {
        int ans = 0;
        for(int i = 0; i < s.size(); i ++)
        {
            int j = i;
            while(j < s.size() && s[j] != t[j])
                j ++;
            ans += j - i > 0;
            i = j;
        }
        return ans;
    }
    
    void solve() 
    {
        int n;
        string s;
        cin >> n >> s;
        string t = s, x = s;
        for(int i = 0; i < n; i ++)
            if(i & 1) t[i] = '1';
            else t[i] = '0';
        for(int i = 0; i < n; i ++)
            if(i & 1) x[i] = '0';
            else x[i] = '1';
        cout << min(cmp(s, t), cmp(s, x)) << endl;
    }            
    
    int main()
    {
        int t = 1;
        // cin >> t;
        while(t --)
            solve();
    }
    
    • 1

    信息

    ID
    507
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    (无)
    递交数
    5
    已通过
    2
    上传者