Binary Queries

Some problems appear hard though they are very easy. Today Aakash is stuck in a range query problem. He has been given an array with only numbers 0 and 1. There are two types of queries -

0 L R: Check whether the number formed from the array elements L to R is even or odd and print EVEN or ODD respectively. Number formation is the binary number from the bits status in the array L to R

1 X : Flip the Xth bit in the array

Indexing is 1 based

Example:

Input:  n = 5, q = 2,  a = {1, 0, 1, 1, 0}, queries = {{1, 2}, {0, 1, 4}}
Output: ODD

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void binaryQueries(int nint qint a[],
                   vector<vector<int>> &queries)
{
    int arr[n + 1];
    for (int i = 1i <= ni++)
        arr[i] = a[i - 1];
    for (int i = 0i < qi++)
    {
        int c = queries[i][0];

        if (c == 0)
        {
            int x = queries[i][1];
            int y = queries[i][2];
            if (arr[y] == 1)
                cout << "ODD\n";
            else
                cout << "EVEN\n";
        }
        else
        {
            int x = queries[i][1];
            arr[x] = !arr[x];
        }
    }
}
int main()
{

    int n = 5q = 2;

    int a[n] = {10110};

    vector<vector<int>> queries = {{12},
                                   {014}};

    binaryQueries(nqaqueries);

    return 0;
}


No comments:

Post a Comment