
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
Advertisements