Description
There is a chocolate, is composed of black and white small pieces. Xiao Ming is very fond of this chocolate, and the absolute difference between the number of black pieces and the number of white pieces is not more
than 1, he think this chocolate is perfect.
Now Xiao Ming has one this chocolate in his hand, maybe it is not perfect.He will cut it into small blocks, making these small blocks are all perfect, he wanted to know how many times he will cut at least.
Input
There are multiple test cases.
For each test case.There is only one string composed of ‘0’ and ‘1’.’0’ is for the white piece while ‘1’ for the black piece.The length of the string for each case is not more than 100000.
Output
For each test case, you output one line “Case #%d:%d”
Sample Input
10011100010000 1
Sample Output
Case #1:3 Case #2:0
Hint
Source
Author
HNU
题意:当黑色小块与白色小块的个数相差的绝对值不大于1,就是一块Perfect Chocolate,给出的巧克力可能不是Perfect的,问最少切几下可以让所有的巧克力都是Perfect
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
int c[100005],sumb,sumw;
int main(){
string str;int cas=0;
while(cin>>str){
int len=str.length();
sumb=sumw=0;
for(int i=0;i<len;i++){
if(str[i]=='1') sumb++,c[i]=1;
else sumw++,c[i]=-1;
}
int ans=0;
cout<<"Case #"<<++cas<<":";
if(abs(sumb-sumw)<=1) {cout<<ans<<endl;continue;}
int now=0;
while(now<len){
int sum=0,pos=now;
for(int i=now;i<len;i++){
sum+=c[i];
if(sum==1||sum==-1||!sum) pos=i;
}
ans++;
now=pos+1;
}
cout<<ans-1<<endl;
}
}
#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
string str;
int GetAns(){
int n = str.length();
int sum = 0;
for (int i = 0; i < n; i++){
if (str[i] == '0') sum++;
else sum--;
}
if (sum < 0) sum = -sum;
if (sum > 0) sum--;
return sum;
}
int main(){
int ca = 0;
while (cin >> str){
ca++;
int ans = GetAns();
cout << "Case #" << ca << ":" << ans << endl;
}
return 0;
}