Self Destructing Strings help

Hi,
Can someone tell me what is wrong with my code?

https://www.codechef.com/viewsolution/40632438

I even tried generating random testcases and running it through a correct submission and my submission and it was giving same output.

Thanks in advance.

There’s lot of superfluity in your solution try to keep your code short and precise :slight_smile: .

CODE
#include<bits/stdc++.h>
#define ar array 
using namespace std ;
void solve(){
  string s ;
  cin >> s  ;
  ar<int,2>a={0,0} ;
  for(char x:s)
    a[x-'0']++ ;
  cout << (a[0]==0||a[1]==0||(a[0]+a[1])&1?-1:abs(a[0]-a[1])/2) << '\n' ;
}
signed main(){
  int TC ;
  cin >> TC ;
  while(TC--)
    solve() ;
}

In this problem you was not having to find how many number of operations are required by checking the consecutive bits .
it was just observation .
if length of string is odd you cant do it at all
because you need equal number of ones to destroy equal number of zeros
now you can cancel the zero by adjacent one and one by zero
if number of ones and zero are equal you need not to do any operation as they kill themselves
if not equal you was having to find the number required to make them equal
like 11001111
in this case we have to increase zero to four so we need two operations
11000001
in this case you have to increase no of ones as it is less than length/2 ;
in short both parities should be equal to length/2
you have to calculate the number by which you have increase the parity .
if you observe properly if number of parities are equal the cancel each other irrespective of the position of the parity .
just try to do it using pen and paper and see the
in second testcase the changed second bit
if you will change the last bit still the string will destroy it self
1100 here middle will destroyed
and the remaing is destroyed .
1001
in this no explaination required i think

Thanks for your help everyone.

observe neatly if you have equal number of parities irrespective of their position you can cancel them .

1 Like

Try : 100000
Output should be 2 your code shows -1;

Because if 0’s are more you are checking if s[i]==0 and s[i+1]==1, which is not always the case to make a 0->1 like in the above example. (0 at 1st index can be inverted to 1 using 1at index 0.)

Thnx for pointing it out
I misinterpreted the problem statement

I thought s[i] can only be flipped if s[i+1] is different
But the statement says if s[i] != s[i+1] then any of s[i] or s[i+1] can be flipped.