You are given a bit array (0 and 1) of size
. Your task is to perform queries. In each query, you have to toggle all the bits from the index to ( and inclusive). After performing all the queries, print the count of all the set bits and newly updated a
Example:
Input: n = 6, a[] = {1, 0, 1, 1, 0, 1}, q = 3, queries = {{1, 3}, {4, 5}, {2, 5}}
Output:
3 0 0 1 1 0 1
Approach:
C++
#include <bits/stdc++.h>using namespace std;void binaryMovement(int n, int a[], int q,vector<vector<int>> &queries){int arr[n + 1];int arr2[n + 1] = {0};for (int i = 1; i <= n; i++){arr[i] = a[i - 1];}for (int i = 0; i < q; i++){int a = queries[i][0], b = queries[i][1];arr2[a]++;arr2[b + 1]--;}for (int i = 1; i <= n; i++){arr2[i] = arr2[i] + arr2[i - 1];}for (int i = 1; i <= n; i++){if (arr2[i] % 2 == 1)arr[i] = 1 - arr[i];}int c = 0;for (int i = 1; i <= n; i++){if (arr[i] == 1)c++;}cout << c << "\n";for (int i = 1; i <= n; i++){cout << arr[i] << " ";}}int main(){int n = 6;int a[] = {1, 0, 1, 1, 0, 1};int q = 3;vector<vector<int>> queries = {{1, 3}, {4, 5}, {2, 5}};binaryMovement(n, a, q, queries);return 0;}
No comments:
Post a Comment