Mad Max is feeling too much boredom due to lockdown. so she decided to do some activity. In her house, there are N rooms continuously numbered from 1 to N. Initially some doors are in open and some are in close. doors that are open represented as 1 and doors that are closed are represented as 0.
Now her boyfriend will give q times a range L to R in which she has to flip the doors in the range L to R (inclusively).(open the doors that are in close and close the doors that are in open.)After performing q operations print the state of each door from 1 to N.
Example:
Input: n = 6, arr[n] = {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 flipTheDoor(int n, int arr[], int q,vector<vector<int>> &queries){int a[n + 1];int add[n + 1];for (int i = 1; i <= n; i++)a[i] = arr[i - 1];for (int i = 0; i < q; i++){int L = queries[i][0];int R = queries[i][1];add[L]++;add[++R]--;}int ans = 0;for (int i = 1; i <= n; i++){add[i] += add[i - 1];a[i] = (a[i] + add[i]) & 1;ans += a[i];}cout << ans << '\n';for (int i = 1; i <= n; i++)cout << a[i] << " \n"[i == n];}int main(){int n = 6;int arr[n] = {1, 0, 1, 1, 0, 1};int q = 3;vector<vector<int>> queries = {{1, 3}, {4, 5}, {2, 5}};flipTheDoor(n, arr, q, queries);return 0;}
No comments:
Post a Comment