// C++ program to find the maximum
// distance between two elements
// with value 1 within a subarray (l, r)
#include <bits/stdc++.h>
using namespace std;
// Structure for each node
// in the segment tree
struct node {
int l1, r1;
int max1;
} seg[100001];
// A utility function for
// merging two nodes
node task(node l, node r)
{
node x;
x.l1 = (l.l1 != -1) ? l.l1 : r.l1;
x.r1 = (r.r1 != -1) ? r.r1 : l.r1;
x.max1 = max(l.max1, r.max1);
if (l.l1 != -1 && r.r1 != -1)
x.max1 = max(x.max1, r.r1 - l.l1);
return x;
}
// A recursive function that constructs
// Segment Tree for given string
void build(int qs, int qe, int ind, int arr[])
{
// If start is equal to end then
// insert the array element
if (qs == qe) {
if (arr[qs] == 1) {
seg[ind].l1 = seg[ind].r1 = qs;
seg[ind].max1 = INT_MIN;
}
else {
seg[ind].l1 = seg[ind].r1 = -1;
seg[ind].max1 = INT_MIN;
}
return;
}
int mid = (qs + qe) >> 1;
// Build the segment tree
// for range qs to mid
build(qs, mid, ind << 1, arr);
// Build the segment tree
// for range mid+1 to qe
build(mid + 1, qe, ind << 1 | 1, arr);
// merge the two child nodes
// to obtain the parent node
seg[ind] = task(
seg[ind << 1],
seg[ind << 1 | 1]);
}
// Query in a range qs to qe
node query(int qs, int qe,
int ns, int ne, int ind)
{
node x;
x.l1 = x.r1 = -1;
x.max1 = INT_MIN;
// If the range lies in this segment
if (qs <= ns && qe >= ne)
return seg[ind];
// If the range is out of the bounds
// of this segment
if (ne < qs || ns > qe || ns > ne)
return x;
// Else query for the right and left
// child node of this subtree
// and merge them
int mid = (ns + ne) >> 1;
node l = query(qs, qe, ns,
mid, ind << 1);
node r = query(qs, qe,
mid + 1, ne,
ind << 1 | 1);
x = task(l, r);
return x;
}
// Driver code
int main()
{
int arr[] = { 1, 1, 0,
1, 0, 1,
0, 1, 0,
1, 0, 1,
1, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
int l = 3, r = 9;
// Build the segment tree
build(0, n - 1, 1, arr);
// Query in range 3 to 9
node ans = query(l, r, 0, n - 1, 1);
cout << ans.max1 << "\n";
return 0;
}