This is CODE APOCALYPSE!! People are fighting against each other, not for food, money, or life but for points. There are n people and each of them is fighting for some number of points.
Now you will be given q queries containing l and r. You have to tell the maximum number of people who are fighting for same number of point from l to r.
Example:
Input: n = 6, q = 2, arr = {1, 1, 1, 2, 3, 3},queries = {{3, 6}, {1, 6}}
Output:
2 3
Approach:
C++
#include <bits/stdc++.h>using namespace std;long long a[1000000 + 10];struct node{long long rf, lf, mf;} tree[1000000];void build(long long no, long long start, long long end){if (start == end){tree[no].lf = tree[no].rf = tree[no].mf = 1;return;}long long mid = (start + end) >> 1;build(no * 2, start, mid);build(2 * no + 1, mid + 1, end);if (a[mid] == a[mid + 1]){tree[no].lf = tree[2 * no].lf +tree[2 * no + 1].lf * (a[start] == a[mid]);tree[no].rf = tree[2 * no + 1].rf + tree[2 *no].rf * (a[end] == a[mid + 1]);long long p = tree[2 * no].rf + tree[2 * no + 1].lf;tree[no].mf = max(p, max(tree[2 * no].mf, tree[2 *no + 1].mf));}else{tree[no].lf = tree[2 * no].lf;tree[no].rf = tree[2 * no + 1].rf;tree[no].mf = max(tree[2 * no + 1].mf,tree[2 * no].mf);}}long long query(long long no, long long start,long long end, long long l, long long r){if (start > end or start > r or l > end)return 0;if (l <= start and end <= r)return tree[no].mf;long long mid = (start + end) / 2;long long p1 = query(2 * no, start, mid, l, r);long long p2 = query(2 * no + 1, mid + 1, end, l, r);if (a[mid] == a[mid + 1]){long long p = min(tree[2 * no].rf, mid - l + 1) +min(tree[2 * no + 1].lf, r - mid);return max(p, max(p1, p2));}elsereturn max(p1, p2);}int main(){long long n = 6, q = 2;vector<int> arr = {1, 1, 1, 2, 3, 3};vector<vector<int>> queries = {{3, 6}, {1, 6}};for (int i = 1; i <= n; i++)a[i] = arr[i - 1];build(1, 1, n);for (int i = 0; i < q; i++){int l = queries[i][0];int r = queries[i][1];cout << query(1, 1, n, l, r) << "\n";}return 0;}
No comments:
Post a Comment