Problem DescriptionFor a 01 string, you can change one 0 to 1 at a time, or change one 1 to 0. So, how many times do you have to change a 01 string S into an ordered 01 string (an ordered 01 string that satisfies all 0 1 strings before all 01)?
inputThe first line is an integer T that represents the number of groups of test data. (1≤T≤10)
The following T-line contains a 01 string S per line. (1≤| s| ≤1000)
OutputThe minimum number of changes required for each set of test data outputs.
Sample Input3
000111
010001
100000
Sample Output0
1
1
ideas for solving problemsSuppose the 01 string s length is Len, the last transformation completes 01 string before the K (0-len) character is 0, after Len-k 1, then compares with the original state, thus confirms how many times altogether transforms.
However, if the direct contrast is the time complexity O (N2), so you need to preprocess it, only to calculate the number of each prefix string of 1 and the number of 0 in the suffix string loop, the time responsible for the degree O (n). For example, when 1001101 k=0, the prefix string is empty, with 0 1; the suffix string is 1001101, of which there are 3 0, and the number is 0+3=3
K=1, the prefix string is 1, which has a 1 suffix string of 001101, of which there are 3 0, and the number is 1+3=4
k=2, the prefix string is 10, which has a 1 suffix string of 01101, of which 2 0, the number of 1+2=3 k=3, the prefix string is 100, which has a 1 suffix string of 1101, which has a 0, the number is 1+1=2 k=4, The prefix string is 1001, which has 2 1; the suffix string is 101, which has a 0, and the number is 2+1=3
k=5, the prefix string is 10011, which has 3 1; the suffix string is 01, where there is a 0, the number is 3+1=4 k=6, the prefix string is 100110, which has 3 1; the suffix string is 1, 0 0, and the number is 3+0=3 k=7, The prefix string is 1001101, where there are 4 1; the suffix string is empty, with 0 0 in the number of 4+0=4
Code:
Main.cpp//hiho164/////Created by small zhe on 17/8/21. copyright©2017 years small Zhe.
All rights reserved.
#include <iostream> #include <string.h> #include <string> using namespace std;
int main (int argc, const char * argv[]) {int n;
cin>>n;
int qian[1001];
int hou[1001];
string S;
String slist[10];
for (int i=0; i<n; i++) {cin>>slist[i];
for (int i=0; i<n; i++) {s=slist[i];
int qiancount1=0;
for (int j=0; j<s.length (); j + +) {if (s[j]== ' 1 ') {qiancount1++;
} qian[j]=qiancount1;
int houcount0=0;
for (int j=s.length () -1;j>=0; j--) {if (s[j]== ' 0 ') {houcount0++;
} hou[j]=houcount0;
} hou[s.length ()]=0; int min=hou[0];//starts with 0 for (int j=0; j<s.length (); j + +) {int temp=qian[J]+HOU[J+1];
if (min>temp) {min=temp;
}} cout<<min<<endl;
return 0;
}