Question meaning:
Given a string consisting of 01, you can change 0 to 1 at will.0 to 1 or1 to 0 1 to 01 to 0 . Ask the minimum number of changes so that all subsequences of the string do not exist101 1011 0 1 or010 010010。
Idea: Change
the string to 0001111, 111000, 00000, 111111 0001111, 111000, 00000, 1111110 0 0 1 1 1 1 , 1 1 1 0 0 0 , 0 0 0 0 0 , 1 1 1 1 1 1 format is fine, for the i-th element, we either turnits left side + itself into 1, Its right side becomes 0, its left side + itself becomes 1, its right side becomes 0It 's the left side+Since has changed to 1 , which is the right edge variable to 0 , either toits left themselves into + 0, it becomes a right + left its own becomes zero, it becomes a rightIt 's the left side+Since it has changed to 0 , which is the right edge variable to 1 .
I used a tree array (review, the prefix sum is okay), use the tree array to find the number of 0s and 1s in front of the i-th element (including the i-th), and then calculate the above two cases Change the number of times and take the minimum value.
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
const int inf = 0x7ffffff;
string s;
int v[2][N];//用来构建两个数,一个存0的个数,一个存1的个数。
void add(int i, int k) {
//添加元素
while(i < N) {
v[k][i] += 1;
i += i & (-i);
}
}
int query(int i, int k) {
//查询[0,i]区间,有多少个0或多少个1。
int ans = 0;
while(i) {
ans += v[k][i];
i -= i & (-i);
}
return ans;
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int t;
cin >> t;
while(t--) {
memset(v, 0, sizeof v);
cin >> s;
int ans1, ans2, sum1 = 0, sum2 = 0, mx = inf;
for(int i=0; i<s.size(); i++) {
if(s[i] == '0'){
add(i+1, 0);
sum1++;
}
else {
add(i+1, 1);
sum2++;
}
}
for(int i=0; i<s.size(); i++) {
ans1 = query(i+1, 0);//查询0的个数
ans2 = query(i+1, 1);//查询1的个数
mx = min(mx, ans1+sum2-ans2);//变成1111000形式。
mx = min(mx, ans2+sum1-ans1);//变成0000111形式。
}
cout << mx << endl;//最小值
}
return 0;
}