Reverse Binary Strings

Reverse Binary Strings
Insert picture description here

Ideas

This kind of problem focuses on the result, not the alternating process

If it hits 00 000 0 , then find the next11 111 1 , the middle0 1 0~10 1  all reverse.

So a 00 000 0 , you need to consume a11 111 1 to restore01/10 01/1001/10

So record 00, 11 00, 110 0 , the number of 1 1 c 1, c 2 c1,c2c1,c2

Just take the maximum value between the two.

If c 1! = C 2 c1!= c2c1!=c 2 , there may be001 001 at theend0 0 1 is not consumed in pairs at this time.

#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
int n;
char s[maxn];
 
void work() {
    
    
    scanf("%d", &n);
    scanf("%s", s);
    int ans1 = 0, ans0 = 0;
    for (int i = 0; i < n - 1; i++) {
    
    
        if (s[i] == '1' && s[i + 1] == '1') ans1++;
        if (s[i] == '0' && s[i + 1] == '0') ans0++;
    }
    printf("%d\n", max(ans1, ans0));
}
 
int main() {
    
    
    int _;
    scanf("%d", &_);
    while (_--) {
    
    
        work();
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43601103/article/details/112981934