Official
Solution 2. find consecutive
C - Calculator Editorial by en_translator
As a general rule, we need to press one button per one character to display \(S\). The exception is 0
, where 00
button is available.
If there is a portion of \(z\) consecutive 0
s, it can be entered by pressing the button \(\lceil z/2 \rceil\) times. (\(\lceil x \rceil\) is \(x\) rounded up.)
Solution 1. press greedily from the beginning
By pressing the buttons as follows, one can minimize the number of operations required.
- If the uninputted part starts with two consecutive
0
s, then press them at once. - Otherwise, insert the first character.
This can be simulated using a loop.
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
int l=s.size();
int p=0,res=0;
while(p<l){
res++;
if((p+1)<l && s[p]=='0' && s[p+1]=='0'){p+=2;}
else{p++;}
}
cout << res << "\n";
return 0;
}
Solution 2. find consecutive 0
s
One can (exhaustively) enumerate consecutive occurrences of 0
, and for each run, count how many 0
there are, to find the answer.
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
int l=s.size();
int z=0,res=0;
for(auto &nx : s){
if(nx=='0'){
z++;
}
else{
res+=(z+1)/2;
z=0;
res++;
}
}
res+=(z+1)/2;
cout << res << "\n";
return 0;
}
posted:
last update: