I have written the following code for the problem:
Alice has an array of NN integers — A_1, A_2, ..., A_N. She wants the product of all the elements of the array to be a non-negative integer. That is, it can be either 00 or positive. But she doesn't want it to be negative.
To do this, she is willing to remove some elements of the array. Determine the minimum number of elements that she will have to remove to make the product of the array's elements non-negative.
Code :
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;cin>>t;
while(t--){
int n;cin>>n;
int res=0;
bool flag=false;
for(int i=0;i<n;i ){
int f;cin>>f;
if(f<0){
res ;
}
if(f==0){
flag=true;
break;
}
}
if(res%2==0 || flag==true){
cout<<0<<endl;
}
else{
cout<<1<<endl;
}
}
return 0;
}
I know that if I remove the break statement, the code will get correct answer for all test cases. But why can I not use break, as it will only terminate the for loop?
CodePudding user response:
You need to read all input even if you do know the answer already:
for(int i=0;i<n;i ){
int f;cin>>f;
// ^^ ----------- !!!
If you break from that loop then the numbers for the current test case are still in the stream, waiting to be read. And you do read them for the next test case.
Consider this input for two test cases
0 1 2 3
2 4 0 5 1 2 3 4
But your code with the break
will read for the two test cases this:
0
1 2 3 2 4 0
When do know the answer already you can continue
the loop after reading input:
for(int i=0;i<n;i ){
int f;
cin>>f;
if (flag) continue;
// ...