Flip The door

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 nint arr[], int q,
                 vector<vector<int>> &queries)
{
    int a[n + 1];
    int add[n + 1];
    for (int i = 1i <= ni++)
        a[i] = arr[i - 1];
    for (int i = 0i < qi++)
    {
        int L = queries[i][0];
        int R = queries[i][1];
        add[L]++;
        add[++R]--;
    }
    int ans = 0;
    for (int i = 1i <= ni++)
    {
        add[i] += add[i - 1];
        a[i] = (a[i] + add[i]) & 1;
        ans += a[i];
    }
    cout << ans << '\n';
    for (int i = 1i <= ni++)
        cout << a[i<< \n"[i == n];
}

int main()
{

    int n = 6;
    int arr[n] = {101101};

    int q = 3;

    vector<vector<int>> queries = {{13}, {45}, {25}};
    flipTheDoor(narrqqueries);

    return 0;
}


No comments:

Post a Comment