C++ code to check query for 0 sum


Suppose we have an array A with n elements, the elements are in range -1 to 1. And have another array of pairs for m queries Q like Q[i] = (li, ri). The response to the query will be 1 when the elements of array a can be rearranged so as the sum Q[li] + ... + Q[ri] = 0, otherwise 0. We have to find answers of all queries.

So, if the input is like A = [-1, 1, 1, 1, -1]; Q = [[1, 1], [2, 3], [3, 5], [2, 5], [1, 5]], then the output will be [0, 1, 0, 1, 0]

Steps

To solve this, we will follow these steps −

n := size of A
m := size of Q
z := 0
for initialize , i := 0, when i < n, update (increase i by 1), do:
   z := z + (1 if a < 0, otherwise 0)
if z > n - z, then:
   z := n - z
for initialize i := 0, when i < m, update (increase i by 1), do:
   l := Q[i, 0]
   r := Q[i, 1]
   print 1 if (((r - l) mod 2 is 1 and (r - l + 1) / 2) <= z),
otherwise 0

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A, vector<vector<int>> Q){
   int n = A.size();
   int m = Q.size();
   int z = 0;
   for (int a, i = 0; i < n; ++i)
      z += a < 0;
   if (z > n - z)
      z = n - z;
   for (int i = 0; i < m; i++){
      int l = Q[i][0];
      int r = Q[i][1];
      cout << (((r - l) % 2 && (r - l + 1) / 2) <= z) << ", ";
   }
}
int main(){
   vector<int> A = { -1, 1, 1, 1, -1 };
   vector<vector<int>> Q = { { 1, 1 }, { 2, 3 }, { 3, 5 }, { 2, 5 }, { 1, 5 } };
   solve(A, Q);
}

Input

{ -1, 1, 1, 1, -1 }, { { 1, 1 }, { 2, 3 }, { 3, 5 }, { 2, 5 }, { 1, 5
} }

Output

1, 0, 1, 0, 1,

Updated on: 30-Mar-2022

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements