import java.io.*;
import java.util.*;
class GFG
{
static int getMid(int s, int e)
{
return s + (e - s) / 2;
}
static int getSumUtil(int[] tree, int[] lazy, int ss,
int se, int qs, int qe, int si)
{
if (lazy[si] != 0)
{
tree[si] = (se - ss + 1) - tree[si];
if (ss != se)
{
lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
}
lazy[si] = 0;
}
if (ss > se || ss > qe || se < qs)
return 0;
if (ss >= qs && se <= qe)
return tree[si];
int mid = (ss + se) / 2;
return getSumUtil(tree, lazy, ss, mid, qs, qe, 2 * si + 1)
+ getSumUtil(tree, lazy, mid + 1, se, qs, qe, 2 * si + 2);
}
static int getSum(int[] tree, int[] lazy, int n, int qs, int qe)
{
if (qs < 0 || qe > n - 1 || qs > qe)
{
System.out.println("Invalid Input");
return -1;
}
return getSumUtil(tree, lazy, 0, n - 1, qs, qe, 0);
}
static void updateRangeUtil(int[] tree, int[] lazy, int si,
int ss, int se, int us, int ue)
{
if (lazy[si] != 0)
{
tree[si] = (se - ss + 1) - tree[si];
if (ss != se)
{
lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
}
lazy[si] = 0;
}
if (ss > se || ss > ue || se < us)
return;
if (ss >= us && se <= ue)
{
tree[si] = (se - ss + 1) - tree[si];
if (ss != se)
{
lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
}
return;
}
int mid = (ss + se) / 2;
updateRangeUtil(tree, lazy, si * 2 + 1, ss, mid, us, ue);
updateRangeUtil(tree, lazy, si * 2 + 2, mid + 1, se, us, ue);
tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2];
}
static void updateRange(int[] tree, int[] lazy,
int n, int us, int ue)
{
updateRangeUtil(tree, lazy, 0, 0, n - 1, us, ue);
}
static int constructSTUtil(int arr[], int ss,
int se, int[] tree, int si)
{
if (ss == se)
{
tree[si] = arr[ss];
return arr[ss];
}
int mid = getMid(ss, se);
tree[si] = constructSTUtil(arr, ss, mid, tree, si * 2 + 1)
+ constructSTUtil(arr, mid + 1, se, tree, si * 2 + 2);
return tree[si];
}
static int[] constructST(int arr[], int n)
{
int x = (int) Math.ceil(Math.log(n) / Math.log(2));
int max_size = 2 * (int) Math.pow(2, x) - 1;
int[] tree = new int[max_size];
constructSTUtil(arr, 0, n - 1, tree, 0);
return tree;
}
static int[] constructLazy(int arr[], int n)
{
int x = (int) Math.ceil(Math.log(n) / Math.log(2));
int max_size = 2 * (int) Math.pow(2, x) - 1;
int[] lazy = new int[max_size];
return lazy;
}
public static void main(String[] args)
{
int[] arr = {0, 0, 0, 0};
int n = arr.length;
int[] tree = constructST(arr, n);
int[] lazy = constructLazy(arr, n);
System.out.println("Black Pieces in given range = " +
getSum(tree, lazy, n, 0, 3));
updateRange(tree, lazy, n, 1, 2);
System.out.println("Black Pieces in given range = " +
getSum(tree, lazy, n, 0, 1));
updateRange(tree, lazy, n, 0, 3);
System.out.println("Black Pieces in given range = " +
getSum(tree, lazy, n, 0, 3));
}
}