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 process query operation on binary array
Suppose we have an array A with n elements and another list of queries Q with q queries. each Query[i] contains a pair (x, k). When we process a query, for x: decrease the value of A[x] by 1. For k, print kth largest element. Initially all elements in A is either 0 or 1.
So, if the input is like A = [1, 1, 0, 1, 0]; Q = [[2, 3], [1, 2], [2, 3], [2, 1], [2, 5]], then the output will be [1, 1, 1, 0]
Steps
To solve this, we will follow these steps −
n := size of A m := 0 for initialize i := 0, when i < n, update (increase i by 1), do: if A[i] is non-zero, then: (increase m by 1) for initialize j := 0, when j < size of Q, update (increase j by 1), do: x := Q[j, 0] k := Q[j, 1] if x is same as 0, then: if A[k] is non-zero, then: (decrease m by 1) Otherwise (increase m by 1) A[k] := A[k] XOR 1 Otherwise if m >= k, then: print 1 Otherwise print 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 = 0;
for (int i = 0; i < n; i++){
if (A[i])
m++;
}
for (int j = 0; j < Q.size(); j++){
int x = Q[j][0];
int k = Q[j][1];
if (x == 0){
if (A[k])
m--;
else
m++;
A[k] ^= 1;
}
else{
if (m >= k)
cout << 1 << ", ";
else
cout << 0 << ", ";
}
}
}
int main(){
vector<int> A = { 1, 1, 0, 1, 0 };
vector<vector<int>> Q = { { 1, 2 }, { 0, 1 }, { 1, 2 }, { 1, 0 },{ 1, 4 } };
solve(A, Q);
}
Input
{ 1, 1, 0, 1, 0 }, { { 1, 2 }, { 0, 1 }, { 1, 2 }, { 1, 0 }, { 1, 4 }}
Output
1, 1, 1, 0,
Advertisements