Reunion of 1's

You are given a string of size n consisting of 0s and/or 1s. You have to perform total k queries and there are two types of queries possible:
1. "1" (without quotes): Print length of the longest sub-array which consists of all '1'.
2. "2 X" (without quotes): where X is an integer between 1 to n. In this query, you will change the character at the Xth position to '1' (It is possible that the character at i-th position was already '1').

Example:

Input:  n = 5, q = 7,s = "00000",queries = {{1}, {2, 3}, {1}, {2, 5}, {1}, {2, 4}, {1}}

Output:

0 1 1 3

Approach:

C++

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

int fparent(int aint parent[])
{
    if (a == parent[a])
        return a;
    return parent[a] = fparent(parent[a], parent);
}

int maxi;

void merge(int aint bint parent[], int sz[])
{
    a = fparent(aparent), b = fparent(bparent);
    if (a == b)
        return;

    if (sz[a] >= sz[b])
    {
        sz[a] += sz[b];
        maxi = max(maxisz[a]);
        sz[b] = 0;
        parent[b] = a;
    }
    else
    {
        parent[a] = b;
        sz[b] += sz[a];
        maxi = max(maxisz[b]);
        sz[a] = 0;
    }
}

void reunionOne(int nint qstring s,
                vector<vector<int>> &queries)
{

    int parent[n + 1], sz[n + 1];
    for (int i = 0i <= ni++)
        parent[i] = isz[i] = 1;

    maxi = 0;
    for (int i = 1i < ni++)
    {
        if (s[i] == s[i - 1] && s[i] == '1')
            merge(ii - 1parentsz);
    }

    for (int i = 0i < qi++)
    {
        int type = queries[i][0];

        if (type == 1)
        {
            cout << maxi << "\n";
        }
        else
        {
            int x = queries[i][1];

            x--;
            if (s[x] == '1')
                continue;

            s[x] = '1';
            if (x - 1 >= 0 && s[x - 1] == '1')
                merge(x - 1xparentsz);
            if (x + 1 < n && s[x + 1] == '1')
                merge(x + 1xparentsz);

            maxi = max(maxi1);
        }
    }
}

int main()
{
    int n = 5q = 7;
    string s = "00000";
    vector<vector<int>> queries = {{1},
                                   {23},
                                   {1},
                                   {25},
                                   {1},
                                   {24},
                                   {1}};

    reunionOne(nqsqueries);

    return 0;
}


No comments:

Post a Comment