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 n, int q, int a[],vector<vector<int>> &queries){int arr[n + 1];for (int i = 1; i <= n; i++)arr[i] = a[i - 1];for (int i = 0; i < q; i++){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";elsecout << "EVEN\n";}else{int x = queries[i][1];arr[x] = !arr[x];}}}int main(){int n = 5, q = 2;int a[n] = {1, 0, 1, 1, 0};vector<vector<int>> queries = {{1, 2},{0, 1, 4}};binaryQueries(n, q, a, queries);return 0;}
No comments:
Post a Comment