Bootstrap

蓝桥杯2023年第十四届省赛真题-填充

题目来自DOTCPP:

分析:

“ 01 串中出现互不重叠的 00 和 11 子串最多” :对于 11??11来说: 111111 三个 110011 三个,数量相同,但是题目要求我们“ 01 串中出现互不重叠的 00 和 11 子串最多”,因此我们选择111111。

贪心思路:我们可以先对长度为n的01串遍历一遍,将11和00能配对的打上标记。接着在?的位置,对前面一个位置判断,如果它没被打上标记,我们就将?填充为前面那个数字。如果被打上标记的话,就填充后面那个。

贪心代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+20;

string s;
int ans = 0;
bool st[N];

int main(){
    cin >> s;
    
    for(int i = 0; i < s.size(); i++){
        if(st[i]) continue;
        if(s[i] != '?'){
            if(i-1 > 0 && s[i] == s[i-1] && !st[i-1]){
                st[i] = true;
                st[i-1] = true;
                ans ++;
            }
            else if(i+1 < s.size() && s[i] == s[i+1] && !st[i+1]){
                st[i] = st[i+1] = true;
                ans ++;
            }
        }else{
            if(i-1 > 0 && !st[i-1]){
                st[i] = st[i-1] = true;
                ans ++;
            }
            else if(i+1 < s.size() && !st[i+1]){
                st[i] = st[i+1] = true;
                ans ++;
            }
        }
    }
    cout << ans;
    return 0;
}

;