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 a, int parent[]){if (a == parent[a])return a;return parent[a] = fparent(parent[a], parent);}int maxi;void merge(int a, int b, int parent[], int sz[]){a = fparent(a, parent), b = fparent(b, parent);if (a == b)return;if (sz[a] >= sz[b]){sz[a] += sz[b];maxi = max(maxi, sz[a]);sz[b] = 0;parent[b] = a;}else{parent[a] = b;sz[b] += sz[a];maxi = max(maxi, sz[b]);sz[a] = 0;}}void reunionOne(int n, int q, string s,vector<vector<int>> &queries){int parent[n + 1], sz[n + 1];for (int i = 0; i <= n; i++)parent[i] = i, sz[i] = 1;maxi = 0;for (int i = 1; i < n; i++){if (s[i] == s[i - 1] && s[i] == '1')merge(i, i - 1, parent, sz);}for (int i = 0; i < q; i++){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 - 1, x, parent, sz);if (x + 1 < n && s[x + 1] == '1')merge(x + 1, x, parent, sz);maxi = max(maxi, 1);}}}int main(){int n = 5, q = 7;string s = "00000";vector<vector<int>> queries = {{1},{2, 3},{1},{2, 5},{1},{2, 4},{1}};reunionOne(n, q, s, queries);return 0;}
No comments:
Post a Comment