The Wayback Machine - https://web.archive.org/web/20240906011649/https://www.geeksforgeeks.org/range-update-query-chessboard-pieces/
Open In App

Range and Update Query for Chessboard Pieces

Last Updated : 27 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given N pieces of chessboard all being ‘white’ and a number of queries Q. There are two types of queries : 

  1. Update : Given indices of a range [L, R]. Paint all the pieces with their respective opposite color between L and R (i.e. white pieces should be painted with black color and black pieces should be painted with white color).
  2. Get : Given indices of a range [L, R]. Find out the number of black pieces between L and R.

Let us represent ‘white’ pieces with ‘0’ and ‘black’ pieces with ‘1’.

Prerequisites: Segment Trees | Lazy Propagation

Examples : 

Input : N = 4, Q = 5
        Get : L = 0, R = 3
        Update : L = 1, R = 2
        Get : L = 0, R = 1
        Update : L = 0, R = 3
        Get : L = 0, R = 3
Output : 0
         1
         2

Explanation : 

  • Query1 : A[] = { 0, 0, 0, 0 } Since initially all pieces are white, number of black pieces will be zero. 
  • Query2 : A[] = { 0, 1, 1, 0 } 
  • Query3 : Number of black pieces in [0, 1] = 1 
  • Query4 : Change the color to its opposite color in [0, 3], A[] = { 1, 0, 0, 1 } 
  • Query5 : Number of black pieces in [0, 3] = 2

Naive Approach : 

  • Update(L, R) : Iterate over the subarray from L to R and change the color of all the pieces (i.e. change 0 to 1 and 1 to 0) 
  • Get(L, R) : To get the number of black pieces, simply count the number of ones in range [L, R]. 

Both update and getBlackPieces() function will have O(N) time complexity. The time complexity in worst case is O(Q * N) where Q is number of queries and N is number of chessboard pieces.

Efficient Approach : 
An efficient method to solve this problem is by using Segment Trees which can reduce the time complexity of update and getBlackPieces functions to O(LogN).

Build Structure: Each leaf node of segment tree will contain either 0 or 1 depending upon the color of the piece (i.e. if the piece is black, node will contain 1 otherwise 0). Internal nodes will contain the sum of ones or number of black pieces of its left child and right child. Thus, the root node will give us the total number of black pieces in the whole array [0..N-1]

Update Structure : Point updates takes O(Log(N)) time but when there are range updates, optimize the updates using Lazy Propagation. Below is the modified update method. 

UpdateRange(ss, se)
1. If current node's range lies completely in update query range.
...a) Value of current node becomes the difference of total count
      of black pieces in the subtree of current node and current
      value of node, i.e. tree[curNode] = (se - ss + 1) - tree[curNode]
...b) Provide the lazy value to its children by setting 
      lazy[2*curNode] = 1 - lazy[2*curNode]
      lazy[2*curNode + 1] = 1 - lazy[2*curNode + 1]

2. If the current node's lazy value is not zero, first update
   it and provide lazy value to children.

3. Partial Overlap of current node's range with query range
...a) Recurse for left and right child
...b) Combine the results of step (a)

Query Structure : Query Structure will also change a bit in the same way as update structure by checking pending updates and updating them to get the correct query output.

Below is the implementation of above approach  

C++




// C++ code for queries on chessboard
#include <bits/stdc++.h>
 
using namespace std;
 
// A utility function to get the
// middle index from corner indexes.
int getMid(int s, int e)
{
    return s + (e - s) / 2;
}
 
/*  A recursive function to get the
    sum of values in given range of
     the array. The following are
    parameters for this function.
    si --> Index of current node in
           the segment tree. Initially
           0 is passed as root is always
           at index 0
    ss & se  --> Starting and ending
                 indexes of the segment
                 represented by current
                 node, i.e., tree[si]
    qs & qe  --> Starting and ending
                 indexes of query range */
int getSumUtil(int* tree, int* lazy, int ss,
               int se, int qs, int qe, int si)
{
    // If lazy flag is set for current node
    // of segment tree, then there are some
    // pending updates. So we need to make
    // sure that the pending updates are done
    // before processing the sub sum query
    if (lazy[si] != 0)
    {
        // Make pending updates to this node.
        // Note that this node represents
        // sum of elements in arr[ss..se]
        tree[si] = (se - ss + 1) - tree[si];
 
        // checking if it is not leaf node
        // because if it is leaf node then
        // we cannot go further
        if (ss != se)
        {
            // Since we are not yet updating
            // children os si, we need to set
            // lazy values for the children
            lazy[si * 2 + 1] =
                 1 - lazy[si * 2 + 1];
             
            lazy[si * 2 + 2] =
                 1 - lazy[si * 2 + 2];
        }
 
        // unset the lazy value for current
        // node as it has been updated
        lazy[si] = 0;
    }
 
    // Out of range
    if (ss > se || ss > qe || se < qs)
        return 0;
 
    // At this point we are sure that pending
    //  lazy updates are done for current node.
    // So we can return value (same as it was
    // for query in our previous post)
 
    // If this segment lies in range
    if (ss >= qs && se <= qe)
        return tree[si];
 
    // If a part of this segment overlaps
    // with the given range
    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);
}
 
// Return sum of elements in range from index
// qs (query start) to qe (query end).  It
// mainly uses getSumUtil()
int getSum(int* tree, int* lazy, int n,
           int qs, int qe)
{
    // Check for erroneous input values
    if (qs < 0 || qe > n - 1 || qs > qe)
    {
        printf("Invalid Input");
        return -1;
    }
 
    return getSumUtil(tree, lazy, 0, n - 1,
                      qs, qe, 0);
}
 
/*  si -> index of current node in segment tree
    ss and se -> Starting and ending indexes of
                 elements for which current
                 nodes stores sum.
    us and ue -> starting and ending indexes
                 of update query */
void updateRangeUtil(int* tree, int* lazy, int si,
                     int ss, int se, int us, int ue)
{
    // If lazy value is non-zero for current node
    // of segment tree, then there are some
    // pending updates. So we need to make sure that
    //  the pending updates are done before making
    // new updates. Because this value may be used by
    // parent after recursive calls (See last line
    // of this function)
    if (lazy[si] != 0) {
         
        // Make pending updates using value stored
        // in lazy nodes
        tree[si] = (se - ss + 1) - tree[si];
 
        // checking if it is not leaf node because if
        // it is leaf node then we cannot go further
        if (ss != se)
        {
            // We can postpone updating children
            // we don't need their new values now.
            // Since we are not yet updating children
            // of si, we need to set lazy flags for
            // the children
            lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
            lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
        }
 
        // Set the lazy value for current node
        // as 0 as it has been updated
        lazy[si] = 0;
    }
 
    // out of range
    if (ss > se || ss > ue || se < us)
        return;
 
    // Current segment is fully in range
    if (ss >= us && se <= ue) {
         
        // Add the difference to current node
        tree[si] = (se - ss + 1) - tree[si];
 
        // same logic for checking leaf
        // node or not
        if (ss != se)
        {
            // This is where we store values in
            // lazy nodes, rather than updating
            //  the segment tree itself. Since we
            // don't need these updated values now
            // we postpone updates by storing
            // values in lazy[]
            lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
            lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
        }
        return;
    }
 
    // If not completely in rang, but overlaps,
    // recur for children
    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);
 
    // And use the result of children calls
    // to update this node
    tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2];
}
 
// Function to update a range of values
// in segment tree
/*  us and eu -> starting and ending indexes
    of update query ue  -> ending index
    of update query, diff -> which we need
    to add in the range us to ue */
void updateRange(int* tree, int* lazy,
                 int n, int us, int ue)
{
    updateRangeUtil(tree, lazy, 0, 0, n - 1, us, ue);
}
 
// A recursive function that constructs
// Segment Tree for array[ss..se]. si is
// index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se,
                    int* tree, int si)
{
    // If there is one element in array, store
    // it in current node of segment tree and return
    if (ss == se)
    {
        tree[si] = arr[ss];
        return arr[ss];
    }
 
    // If there are more than one elements, then
    // recur for left and right subtrees and
    // store the sum of values in this node
    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];
}
 
/* Function to construct segment tree from
   given array. This function allocates
   memory for segment tree and calls
   constructSTUtil() to fill the
   allocated memory */
int* constructST(int arr[], int n)
{
    // Allocate memory for segment tree
    
    // Height of segment tree
    int x = (int)(ceil(log2(n)));
 
    // Maximum size of segment tree
    int max_size = 2 * (int)pow(2, x) - 1;
 
    // Allocate memory
    int* tree = new int[max_size];
 
    // Fill the allocated memory st
    constructSTUtil(arr, 0, n - 1, tree, 0);
 
    // Return the constructed segment tree
    return tree;
}
 
/* Function to construct lazy array for
   segment tree. This function allocates
   memory for lazy array  */
int* constructLazy(int arr[], int n)
{
    // Allocate memory for lazy array
 
    // Height of lazy array
    int x = (int)(ceil(log2(n)));
 
    // Maximum size of lazy array
    int max_size = 2 * (int)pow(2, x) - 1;
 
    // Allocate memory
    int* lazy = new int[max_size];
 
    // Return the lazy array
    return lazy;
}
 
// Driver program to test above functions
int main()
{
    // Initialize the array to zero
    // since all pieces are white
    int arr[] = { 0, 0, 0, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Build segment tree from given array
    int* tree = constructST(arr, n);
 
    // Allocate memory for Lazy array
    int* lazy = constructLazy(arr, n);
 
    // Print number of black pieces
    // from index 0 to 3
    cout << "Black Pieces in given range = "
         << getSum(tree, lazy, n, 0, 3) << endl;
 
    // UpdateRange: Change color of pieces
    // from index 1 to 2
    updateRange(tree, lazy, n, 1, 2);
 
    // Print number of black pieces
    // from index 0 to 1
    cout << "Black Pieces in given range = "
         << getSum(tree, lazy, n, 0, 1) << endl;
 
    // UpdateRange: Change color of
    // pieces from index 0 to 3
    updateRange(tree, lazy, n, 0, 3);
 
    // Print number of black pieces
    // from index 0 to 3
    cout << "Black Pieces in given range = "
         << getSum(tree, lazy, n, 0, 3) << endl;
 
    return 0;
}


Java




// Java implementation of the approach
import java.io.*;
import java.util.*;
 
class GFG
{
 
    // A utility function to get the
    // middle index from corner indexes.
    static int getMid(int s, int e)
    {
        return s + (e - s) / 2;
    }
 
    /*
    * A recursive function to get the sum of
    values in given range of the array.
    * The following are parameters for this function.
    * si --> Index of current node in
    *     the segment tree. Initially
    *     0 is passed as root is always
    *     at index 0
    * ss & se --> Starting and ending
    *             indexes of the segment
    *             represented by current
    *             node, i.e., tree[si]
    * qs & qe --> Starting and ending
    *             indexes of query range
    */
    static int getSumUtil(int[] tree, int[] lazy, int ss,
                       int se, int qs, int qe, int si)
    {
         
        // If lazy flag is set for current node
        // of segment tree, then there are some
        // pending updates. So we need to make
        // sure that the pending updates are done
        // before processing the sub sum query
        if (lazy[si] != 0)
        {
 
            // Make pending updates to this node.
            // Note that this node represents
            // sum of elements in arr[ss..se]
            tree[si] = (se - ss + 1) - tree[si];
 
            // checking if it is not leaf node
            // because if it is leaf node then
            // we cannot go further
            if (ss != se)
            {
 
                // Since we are not yet updating
                // children os si, we need to set
                // lazy values for the children
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
 
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
 
            // unset the lazy value for current
            // node as it has been updated
            lazy[si] = 0;
        }
 
        // Out of range
        if (ss > se || ss > qe || se < qs)
            return 0;
 
        // At this point we are sure that pending
        // lazy updates are done for current node.
        // So we can return value (same as it was
        // for query in our previous post)
 
        // If this segment lies in range
        if (ss >= qs && se <= qe)
            return tree[si];
 
        // If a part of this segment overlaps
        // with the given range
        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);
    }
 
    // Return sum of elements in range from index
    // qs (query start) to qe (query end). It
    // mainly uses getSumUtil()
    static int getSum(int[] tree, int[] lazy, int n, int qs, int qe)
    {
         
        // Check for erroneous input values
        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);
    }
 
    /*
    * si -> index of current node in segment tree
    * ss and se -> Starting and ending indexes of
    *             elements for which current
    *             nodes stores sum.
    * us and ue -> starting and ending indexes of
    *             update query
    */
    static void updateRangeUtil(int[] tree, int[] lazy, int si,
                                int ss, int se, int us, int ue)
    {
         
        // If lazy value is non-zero for current node
        // of segment tree, then there are some
        // pending updates. So we need to make sure that
        // the pending updates are done before making
        // new updates. Because this value may be used by
        // parent after recursive calls (See last line
        // of this function)
        if (lazy[si] != 0)
        {
 
            // Make pending updates using value stored
            // in lazy nodes
            tree[si] = (se - ss + 1) - tree[si];
 
            // checking if it is not leaf node because if
            // it is leaf node then we cannot go further
            if (ss != se)
            {
 
                // We can postpone updating children
                // we don't need their new values now.
                // Since we are not yet updating children
                // of si, we need to set lazy flags for
                // the children
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
 
            // Set the lazy value for current node
            // as 0 as it has been updated
            lazy[si] = 0;
        }
 
        // out of range
        if (ss > se || ss > ue || se < us)
            return;
 
        // Current segment is fully in range
        if (ss >= us && se <= ue)
        {
 
            // Add the difference to current node
            tree[si] = (se - ss + 1) - tree[si];
 
            // same logic for checking leaf
            // node or not
            if (ss != se)
            {
 
                // This is where we store values in
                // lazy nodes, rather than updating
                // the segment tree itself. Since we
                // don't need these updated values now
                // we postpone updates by storing
                // values in lazy[]
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
            return;
        }
 
        // If not completely in rang, but overlaps,
        // recur for children
        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);
 
        // And use the result of children calls
        // to update this node
        tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2];
    }
 
    // Function to update a range of values
    // in segment tree
    /*
    * us and eu -> starting and ending indexes
    *             of update query
    * ue -> ending index of update query
    * diff -> which we need to add in the range
    *         us to ue
    */
    static void updateRange(int[] tree, int[] lazy,
                            int n, int us, int ue)
    {
        updateRangeUtil(tree, lazy, 0, 0, n - 1, us, ue);
    }
 
    // A recursive function that constructs
    // Segment Tree for array[ss..se]. si is
    // index of current node in segment tree st
    static int constructSTUtil(int arr[], int ss,
                        int se, int[] tree, int si)
    {
         
        // If there is one element in array, store
        // it in current node of segment tree and return
        if (ss == se)
        {
            tree[si] = arr[ss];
            return arr[ss];
        }
 
        // If there are more than one elements, then
        // recur for left and right subtrees and
        // store the sum of values in this node
        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];
    }
 
    /*
    * Function to construct segment tree from
    given array. This function allocates memory
    for segment tree and calls constructSTUtil()
    to fill the allocated memory
    */
    static int[] constructST(int arr[], int n)
    {
        // Allocate memory for segment tree
 
        // Height of segment tree
        int x = (int) Math.ceil(Math.log(n) / Math.log(2));
 
        // Maximum size of segment tree
        int max_size = 2 * (int) Math.pow(2, x) - 1;
 
        // Allocate memory
        int[] tree = new int[max_size];
 
        // Fill the allocated memory st
        constructSTUtil(arr, 0, n - 1, tree, 0);
 
        // Return the constructed segment tree
        return tree;
    }
 
    /*
    * Function to construct lazy array
    for segment tree. This function allocates
    * memory for lazy array
    */
    static int[] constructLazy(int arr[], int n)
    {
        // Allocate memory for lazy array
 
        // Height of lazy array
        int x = (int) Math.ceil(Math.log(n) / Math.log(2));
 
        // Maximum size of lazy array
        int max_size = 2 * (int) Math.pow(2, x) - 1;
 
        // Allocate memory
        int[] lazy = new int[max_size];
 
        // Return the lazy array
        return lazy;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Initialize the array to zero
        // since all pieces are white
        int[] arr = {0, 0, 0, 0};
        int n = arr.length;
 
        // Build segment tree from given array
        int[] tree = constructST(arr, n);
 
        // Allocate memory for Lazy array
        int[] lazy = constructLazy(arr, n);
 
        // Print number of black pieces
        // from index 0 to 3
        System.out.println("Black Pieces in given range = " +
                                getSum(tree, lazy, n, 0, 3));
 
        // UpdateRange: Change color of pieces
        // from index 1 to 2
        updateRange(tree, lazy, n, 1, 2);
 
        // Print number of black pieces
        // from index 0 to 1
        System.out.println("Black Pieces in given range = " +
                                getSum(tree, lazy, n, 0, 1));
 
        // UpdateRange: Change color of
        // pieces from index 0 to 3
        updateRange(tree, lazy, n, 0, 3);
 
        // Print number of black pieces
        // from index 0 to 3
        System.out.println("Black Pieces in given range = " +
                                getSum(tree, lazy, n, 0, 3));
    }
}
 
// This code is contributed by
// sanjeev2552


Python3




# Python3 code for queries on chessboard
import math
 
# A utility function to get the
# middle index from corner indexes.
def getMid(s, e):
     
    return s + int((e - s) / 2)
 
"""
* A recursive function to get the sum of
values in given range of the array.
* The following are parameters for this function.
* si --> Index of current node in
*     the segment tree. Initially
*     0 is passed as root is always
*     at index 0
* ss & se --> Starting and ending
*             indexes of the segment
*             represented by current
*             node, i.e., tree[si]
* qs & qe --> Starting and ending
*             indexes of query range
"""
def getSumUtil(tree, lazy, ss, se, qs, qe, si):
     
    # If lazy flag is set for current node
    # of segment tree, then there are some
    # pending updates. So we need to make
    # sure that the pending updates are done
    # before processing the sub sum query
    if (lazy[si] != 0):
         
        # Make pending updates to this node.
        # Note that this node represents
        # sum of elements in arr[ss..se]
        tree[si] = (se - ss + 1) - tree[si]
 
        # Checking if it is not leaf node
        # because if it is leaf node then
        # we cannot go further
        if (ss != se):
             
            # Since we are not yet updating
            # children os si, we need to set
            # lazy values for the children
            lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1]
            lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2]
 
        # unset the lazy value for current
        # node as it has been updated
        lazy[si] = 0
 
    # Out of range
    if (ss > se or ss > qe or se < qs):
        return 0
 
    # At this point we are sure that pending
    # lazy updates are done for current node.
    # So we can return value (same as it was
    # for query in our previous post)
 
    # If this segment lies in range
    if (ss >= qs and se <= qe):
        return tree[si]
 
    # If a part of this segment overlaps
    # with the given range
    mid = int((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))
 
# Return sum of elements in range from index
# qs (query start) to qe (query end). It
# mainly uses getSumUtil()
def getSum(tree, lazy, n, qs, qe):
         
    # Check for erroneous input values
    if (qs < 0 or qe > n - 1 or qs > qe):
        print("Invalid Input")
        return -1
 
    return getSumUtil(tree, lazy, 0, n - 1, qs, qe, 0)
 
"""
* si -> index of current node in segment tree
* ss and se -> Starting and ending indexes of
*             elements for which current
*             nodes stores sum.
* us and ue -> starting and ending indexes of
*             update query
"""
def updateRangeUtil(tree, lazy, si, ss, se, us, ue):
     
    # If lazy value is non-zero for current node
    # of segment tree, then there are some
    # pending updates. So we need to make sure that
    # the pending updates are done before making
    # new updates. Because this value may be used by
    # parent after recursive calls (See last line
    # of this function)
    if (lazy[si] != 0):
 
        # Make pending updates using value stored
        # in lazy nodes
        tree[si] = (se - ss + 1) - tree[si]
 
        # Checking if it is not leaf node because if
        # it is leaf node then we cannot go further
        if (ss != se):
             
            # We can postpone updating children
            # we don't need their new values now.
            # Since we are not yet updating children
            # of si, we need to set lazy flags for
            # the children
            lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1]
            lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2]
 
        # Set the lazy value for current node
        # as 0 as it has been updated
        lazy[si] = 0
 
    # Out of range
    if (ss > se or ss > ue or se < us):
        return
 
    # Current segment is fully in range
    if (ss >= us and se <= ue):
         
        # Add the difference to current node
        tree[si] = (se - ss + 1) - tree[si]
 
        # Same logic for checking leaf
        # node or not
        if (ss != se):
             
            # This is where we store values in
            # lazy nodes, rather than updating
            # the segment tree itself. Since we
            # don't need these updated values now
            # we postpone updates by storing
            # values in lazy[]
            lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1]
            lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2]
             
        return
 
    # If not completely in range, but overlaps,
    # recur for children
    mid = int((ss + se) / 2)
    updateRangeUtil(tree, lazy, si * 2 + 1,
                    ss, mid, us, ue)
    updateRangeUtil(tree, lazy, si * 2 + 2,
                    mid + 1, se, us, ue)
 
    # And use the result of children calls
    # to update this node
    tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2]
 
# Function to update a range of values
# in segment tree
"""
* us and eu -> starting and ending indexes
*             of update query
* ue -> ending index of update query
* diff -> which we need to add in the range
*         us to ue
"""
def updateRange(tree, lazy, n, us, ue):
     
    updateRangeUtil(tree, lazy, 0, 0, n - 1, us, ue)
 
# A recursive function that constructs
# Segment Tree for array[ss..se]. si is
# index of current node in segment tree st
def constructSTUtil(arr, ss, se, tree, si):
         
    # If there is one element in array, store
    # it in current node of segment tree and return
    if (ss == se):
     
        tree[si] = arr[ss]
        return arr[ss]
 
    # If there are more than one elements, then
    # recur for left and right subtrees and
    # store the sum of values in this node
    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]
 
"""
* Function to construct segment tree from
given array. This function allocates memory
for segment tree and calls constructSTUtil()
to fill the allocated memory
"""
def constructST(arr, n):
 
    # Allocate memory for segment tree
 
    # Height of segment tree
    x = int(math.ceil(math.log(n) / math.log(2)))
 
    # Maximum size of segment tree
    max_size = 2 * int(math.pow(2, x)) - 1
 
    # Allocate memory
    tree = [0]*max_size
 
    # Fill the allocated memory st
    constructSTUtil(arr, 0, n - 1, tree, 0)
 
    # Return the constructed segment tree
    return tree
 
"""
Function to construct lazy array
for segment tree. This function allocates
memory for lazy array
"""
def constructLazy(arr, n):
 
    # Allocate memory for lazy array
 
    # Height of lazy array
    x = int(math.ceil(math.log(n) / math.log(2)))
 
    # Maximum size of lazy array
    max_size = 2 * int(math.pow(2, x)) - 1
 
    # Allocate memory
    lazy = [0]*max_size
 
    # Return the lazy array
    return lazy
 
# Driver code
 
# Initialize the array to zero
# since all pieces are white
arr = [ 0, 0, 0, 0 ]
n = len(arr)
 
# Build segment tree from given array
tree = constructST(arr, n)
 
# Allocate memory for Lazy array
lazy = constructLazy(arr, n)
 
# Print number of black pieces
# from index 0 to 3
print("Black Pieces in given range =",
      getSum(tree, lazy, n, 0, 3))
 
# UpdateRange: Change color of pieces
# from index 1 to 2
updateRange(tree, lazy, n, 1, 2)
 
# Print number of black pieces
# from index 0 to 1
print("Black Pieces in given range =",
      getSum(tree, lazy, n, 0, 1))
 
# UpdateRange: Change color of
# pieces from index 0 to 3
updateRange(tree, lazy, n, 0, 3)
 
# Print number of black pieces
# from index 0 to 3
print("Black Pieces in given range =",
      getSum(tree, lazy, n, 0, 3))
 
# This code is contributed by suresh07


C#




// C# implementation of the approach
using System;
class GFG {
     
    // A utility function to get the
    // middle index from corner indexes.
    static int getMid(int s, int e)
    {
        return s + (e - s) / 2;
    }
   
    /*
    * A recursive function to get the sum of
    values in given range of the array.
    * The following are parameters for this function.
    * si --> Index of current node in
    *     the segment tree. Initially
    *     0 is passed as root is always
    *     at index 0
    * ss & se --> Starting and ending
    *             indexes of the segment
    *             represented by current
    *             node, i.e., tree[si]
    * qs & qe --> Starting and ending
    *             indexes of query range
    */
    static int getSumUtil(int[] tree, int[] lazy, int ss,
                       int se, int qs, int qe, int si)
    {
           
        // If lazy flag is set for current node
        // of segment tree, then there are some
        // pending updates. So we need to make
        // sure that the pending updates are done
        // before processing the sub sum query
        if (lazy[si] != 0)
        {
   
            // Make pending updates to this node.
            // Note that this node represents
            // sum of elements in arr[ss..se]
            tree[si] = (se - ss + 1) - tree[si];
   
            // checking if it is not leaf node
            // because if it is leaf node then
            // we cannot go further
            if (ss != se)
            {
   
                // Since we are not yet updating
                // children os si, we need to set
                // lazy values for the children
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
   
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
   
            // unset the lazy value for current
            // node as it has been updated
            lazy[si] = 0;
        }
   
        // Out of range
        if (ss > se || ss > qe || se < qs)
            return 0;
   
        // At this point we are sure that pending
        // lazy updates are done for current node.
        // So we can return value (same as it was
        // for query in our previous post)
   
        // If this segment lies in range
        if (ss >= qs && se <= qe)
            return tree[si];
   
        // If a part of this segment overlaps
        // with the given range
        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);
    }
   
    // Return sum of elements in range from index
    // qs (query start) to qe (query end). It
    // mainly uses getSumUtil()
    static int getSum(int[] tree, int[] lazy, int n, int qs, int qe)
    {
           
        // Check for erroneous input values
        if (qs < 0 || qe > n - 1 || qs > qe)
        {
            Console.WriteLine("Invalid Input");
            return -1;
        }
   
        return getSumUtil(tree, lazy, 0, n - 1, qs, qe, 0);
    }
   
    /*
    * si -> index of current node in segment tree
    * ss and se -> Starting and ending indexes of
    *             elements for which current
    *             nodes stores sum.
    * us and ue -> starting and ending indexes of
    *             update query
    */
    static void updateRangeUtil(int[] tree, int[] lazy, int si,
                                int ss, int se, int us, int ue)
    {
           
        // If lazy value is non-zero for current node
        // of segment tree, then there are some
        // pending updates. So we need to make sure that
        // the pending updates are done before making
        // new updates. Because this value may be used by
        // parent after recursive calls (See last line
        // of this function)
        if (lazy[si] != 0)
        {
   
            // Make pending updates using value stored
            // in lazy nodes
            tree[si] = (se - ss + 1) - tree[si];
   
            // checking if it is not leaf node because if
            // it is leaf node then we cannot go further
            if (ss != se)
            {
   
                // We can postpone updating children
                // we don't need their new values now.
                // Since we are not yet updating children
                // of si, we need to set lazy flags for
                // the children
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
   
            // Set the lazy value for current node
            // as 0 as it has been updated
            lazy[si] = 0;
        }
   
        // out of range
        if (ss > se || ss > ue || se < us)
            return;
   
        // Current segment is fully in range
        if (ss >= us && se <= ue)
        {
   
            // Add the difference to current node
            tree[si] = (se - ss + 1) - tree[si];
   
            // same logic for checking leaf
            // node or not
            if (ss != se)
            {
   
                // This is where we store values in
                // lazy nodes, rather than updating
                // the segment tree itself. Since we
                // don't need these updated values now
                // we postpone updates by storing
                // values in lazy[]
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
            return;
        }
   
        // If not completely in rang, but overlaps,
        // recur for children
        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);
   
        // And use the result of children calls
        // to update this node
        tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2];
    }
   
    // Function to update a range of values
    // in segment tree
    /*
    * us and eu -> starting and ending indexes
    *             of update query
    * ue -> ending index of update query
    * diff -> which we need to add in the range
    *         us to ue
    */
    static void updateRange(int[] tree, int[] lazy,
                            int n, int us, int ue)
    {
        updateRangeUtil(tree, lazy, 0, 0, n - 1, us, ue);
    }
   
    // A recursive function that constructs
    // Segment Tree for array[ss..se]. si is
    // index of current node in segment tree st
    static int constructSTUtil(int[] arr, int ss,
                        int se, int[] tree, int si)
    {
           
        // If there is one element in array, store
        // it in current node of segment tree and return
        if (ss == se)
        {
            tree[si] = arr[ss];
            return arr[ss];
        }
   
        // If there are more than one elements, then
        // recur for left and right subtrees and
        // store the sum of values in this node
        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];
    }
   
    /*
    * Function to construct segment tree from
    given array. This function allocates memory
    for segment tree and calls constructSTUtil()
    to fill the allocated memory
    */
    static int[] constructST(int[] arr, int n)
    {
        // Allocate memory for segment tree
   
        // Height of segment tree
        int x = (int) Math.Ceiling(Math.Log(n) / Math.Log(2));
   
        // Maximum size of segment tree
        int max_size = 2 * (int) Math.Pow(2, x) - 1;
   
        // Allocate memory
        int[] tree = new int[max_size];
   
        // Fill the allocated memory st
        constructSTUtil(arr, 0, n - 1, tree, 0);
   
        // Return the constructed segment tree
        return tree;
    }
   
    /*
    * Function to construct lazy array
    for segment tree. This function allocates
    * memory for lazy array
    */
    static int[] constructLazy(int[] arr, int n)
    {
        // Allocate memory for lazy array
   
        // Height of lazy array
        int x = (int) Math.Ceiling(Math.Log(n) / Math.Log(2));
   
        // Maximum size of lazy array
        int max_size = 2 * (int) Math.Pow(2, x) - 1;
   
        // Allocate memory
        int[] lazy = new int[max_size];
   
        // Return the lazy array
        return lazy;
    }
     
  static void Main() {
    // Initialize the array to zero
        // since all pieces are white
        int[] arr = {0, 0, 0, 0};
        int n = arr.Length;
   
        // Build segment tree from given array
        int[] tree = constructST(arr, n);
   
        // Allocate memory for Lazy array
        int[] lazy = constructLazy(arr, n);
   
        // Print number of black pieces
        // from index 0 to 3
        Console.WriteLine("Black Pieces in given range = " +
                                getSum(tree, lazy, n, 0, 3));
   
        // UpdateRange: Change color of pieces
        // from index 1 to 2
        updateRange(tree, lazy, n, 1, 2);
   
        // Print number of black pieces
        // from index 0 to 1
        Console.WriteLine("Black Pieces in given range = " +
                                getSum(tree, lazy, n, 0, 1));
   
        // UpdateRange: Change color of
        // pieces from index 0 to 3
        updateRange(tree, lazy, n, 0, 3);
   
        // Print number of black pieces
        // from index 0 to 3
        Console.WriteLine("Black Pieces in given range = " + getSum(tree, lazy, n, 0, 3));
  }
}
 
// This code is contributed by decode2207.


Javascript




<script>
    // Javascript implementation of the approach
     
    // A utility function to get the
    // middle index from corner indexes.
    function getMid(s, e)
    {
        return s + parseInt((e - s) / 2, 10);
    }
    
    /*
    * A recursive function to get the sum of
    values in given range of the array.
    * The following are parameters for this function.
    * si --> Index of current node in
    *     the segment tree. Initially
    *     0 is passed as root is always
    *     at index 0
    * ss & se --> Starting and ending
    *             indexes of the segment
    *             represented by current
    *             node, i.e., tree[si]
    * qs & qe --> Starting and ending
    *             indexes of query range
    */
    function getSumUtil(tree, lazy, ss, se, qs, qe, si)
    {
            
        // If lazy flag is set for current node
        // of segment tree, then there are some
        // pending updates. So we need to make
        // sure that the pending updates are done
        // before processing the sub sum query
        if (lazy[si] != 0)
        {
    
            // Make pending updates to this node.
            // Note that this node represents
            // sum of elements in arr[ss..se]
            tree[si] = (se - ss + 1) - tree[si];
    
            // checking if it is not leaf node
            // because if it is leaf node then
            // we cannot go further
            if (ss != se)
            {
    
                // Since we are not yet updating
                // children os si, we need to set
                // lazy values for the children
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
    
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
    
            // unset the lazy value for current
            // node as it has been updated
            lazy[si] = 0;
        }
    
        // Out of range
        if (ss > se || ss > qe || se < qs)
            return 0;
    
        // At this point we are sure that pending
        // lazy updates are done for current node.
        // So we can return value (same as it was
        // for query in our previous post)
    
        // If this segment lies in range
        if (ss >= qs && se <= qe)
            return tree[si];
    
        // If a part of this segment overlaps
        // with the given range
        let mid = parseInt((ss + se) / 2, 10);
        return getSumUtil(tree, lazy, ss, mid, qs, qe, 2 * si + 1)
                + getSumUtil(tree, lazy, mid + 1, se, qs, qe, 2 * si + 2);
    }
    
    // Return sum of elements in range from index
    // qs (query start) to qe (query end). It
    // mainly uses getSumUtil()
    function getSum(tree, lazy, n, qs, qe)
    {
            
        // Check for erroneous input values
        if (qs < 0 || qe > n - 1 || qs > qe)
        {
            document.write("Invalid Input");
            return -1;
        }
    
        return getSumUtil(tree, lazy, 0, n - 1, qs, qe, 0);
    }
    
    /*
    * si -> index of current node in segment tree
    * ss and se -> Starting and ending indexes of
    *             elements for which current
    *             nodes stores sum.
    * us and ue -> starting and ending indexes of
    *             update query
    */
    function updateRangeUtil(tree, lazy, si, ss, se, us, ue)
    {
            
        // If lazy value is non-zero for current node
        // of segment tree, then there are some
        // pending updates. So we need to make sure that
        // the pending updates are done before making
        // new updates. Because this value may be used by
        // parent after recursive calls (See last line
        // of this function)
        if (lazy[si] != 0)
        {
    
            // Make pending updates using value stored
            // in lazy nodes
            tree[si] = (se - ss + 1) - tree[si];
    
            // checking if it is not leaf node because if
            // it is leaf node then we cannot go further
            if (ss != se)
            {
    
                // We can postpone updating children
                // we don't need their new values now.
                // Since we are not yet updating children
                // of si, we need to set lazy flags for
                // the children
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
    
            // Set the lazy value for current node
            // as 0 as it has been updated
            lazy[si] = 0;
        }
    
        // out of range
        if (ss > se || ss > ue || se < us)
            return;
    
        // Current segment is fully in range
        if (ss >= us && se <= ue)
        {
    
            // Add the difference to current node
            tree[si] = (se - ss + 1) - tree[si];
    
            // same logic for checking leaf
            // node or not
            if (ss != se)
            {
    
                // This is where we store values in
                // lazy nodes, rather than updating
                // the segment tree itself. Since we
                // don't need these updated values now
                // we postpone updates by storing
                // values in lazy[]
                lazy[si * 2 + 1] = 1 - lazy[si * 2 + 1];
                lazy[si * 2 + 2] = 1 - lazy[si * 2 + 2];
            }
            return;
        }
    
        // If not completely in rang, but overlaps,
        // recur for children
        let mid = parseInt((ss + se) / 2, 10);
        updateRangeUtil(tree, lazy, si * 2 + 1, ss, mid, us, ue);
        updateRangeUtil(tree, lazy, si * 2 + 2, mid + 1, se, us, ue);
    
        // And use the result of children calls
        // to update this node
        tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2];
    }
    
    // Function to update a range of values
    // in segment tree
    /*
    * us and eu -> starting and ending indexes
    *             of update query
    * ue -> ending index of update query
    * diff -> which we need to add in the range
    *         us to ue
    */
    function updateRange(tree, lazy, n, us, ue)
    {
        updateRangeUtil(tree, lazy, 0, 0, n - 1, us, ue);
    }
    
    // A recursive function that constructs
    // Segment Tree for array[ss..se]. si is
    // index of current node in segment tree st
    function constructSTUtil(arr, ss, se, tree, si)
    {
            
        // If there is one element in array, store
        // it in current node of segment tree and return
        if (ss == se)
        {
            tree[si] = arr[ss];
            return arr[ss];
        }
    
        // If there are more than one elements, then
        // recur for left and right subtrees and
        // store the sum of values in this node
        let 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];
    }
    
    /*
    * Function to construct segment tree from
    given array. This function allocates memory
    for segment tree and calls constructSTUtil()
    to fill the allocated memory
    */
    function constructST(arr, n)
    {
        // Allocate memory for segment tree
    
        // Height of segment tree
        let x = parseInt(Math.ceil(Math.log(n) / Math.log(2)), 10);
    
        // Maximum size of segment tree
        let max_size = 2 * parseInt(Math.pow(2, x), 10) - 1;
    
        // Allocate memory
        let tree = new Array(max_size);
        tree.fill(0);
    
        // Fill the allocated memory st
        constructSTUtil(arr, 0, n - 1, tree, 0);
    
        // Return the constructed segment tree
        return tree;
    }
    
    /*
    * Function to construct lazy array
    for segment tree. This function allocates
    * memory for lazy array
    */
    function constructLazy(arr, n)
    {
        // Allocate memory for lazy array
    
        // Height of lazy array
        let x = parseInt(Math.ceil(Math.log(n) / Math.log(2)), 10);
    
        // Maximum size of lazy array
        let max_size = 2 * parseInt(Math.pow(2, x), 10) - 1;
    
        // Allocate memory
        let lazy = new Array(max_size);
        lazy.fill(0);
    
        // Return the lazy array
        return lazy;
    }
     
    // Initialize the array to zero
    // since all pieces are white
    let arr = [0, 0, 0, 0];
    let n = arr.length;
 
    // Build segment tree from given array
    let tree = constructST(arr, n);
 
    // Allocate memory for Lazy array
    let lazy = constructLazy(arr, n);
 
    // Print number of black pieces
    // from index 0 to 3
    document.write("Black Pieces in given range = " +
                      getSum(tree, lazy, n, 0, 3) + "</br>");
 
    // UpdateRange: Change color of pieces
    // from index 1 to 2
    updateRange(tree, lazy, n, 1, 2);
 
    // Print number of black pieces
    // from index 0 to 1
    document.write("Black Pieces in given range = " +
                      getSum(tree, lazy, n, 0, 1) + "</br>");
 
    // UpdateRange: Change color of
    // pieces from index 0 to 3
    updateRange(tree, lazy, n, 0, 3);
 
    // Print number of black pieces
    // from index 0 to 3
    document.write("Black Pieces in given range = " + getSum(tree, lazy, n, 0, 3));
     
    // This code is contributed by divyeshrabadiy07.
</script>


Output

Black Pieces in given range = 0
Black Pieces in given range = 1
Black Pieces in given range = 2

Time Complexity : Each query and each update will take O(Log(N)) time, where N is the number of chessboard pieces. Hence for Q queries, worst case complexity will be (Q * Log(N))

Auxiliary Space: O(n)

Related Topic: Segment Tree



Previous Article
Next Article

Similar Reads

Divide chocolate bar into pieces, minimizing the area of invalid pieces
Given a 2d array, arr[][] and a piece of the chocolate bar of dimension N × M, the task is to find the minimum possible sum of the area of invalid pieces by dividing the chocolate bar into one or more pieces where a chocolate piece is called invalid if the dimension of that piece doesn't match any given pair. Note: A chocolate piece can be cut vert
15+ min read
Range Update without using Lazy Propagation and Point Query in a Segment Tree
Given an array arr[] consisting of N 0s and a 2D array Q[][] consisting of queries of the following two types: 1 L R X: Increment all the elements in the range [L, R] by X.2 X: Print elements at Xth index of the array. Input: arr[] = { 0, 0, 0, 0, 0 }, Q[][] = { { 1, 0, 2, 100 }, { 2, 1 }, { 1, 2, 3, 200 }, { 2, 2 }, { 4 } } Output: 100 300 0 Expla
13 min read
Segment Tree | Set 2 (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1. Also, change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1 and then find the maximum element of given range with updated values.Example : Input : {1, 3, 5, 7, 9, 11}
15+ min read
Iterative Segment Tree (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. The task is to perform the following operation: Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1.Change value of a specified element of the array to a new value x. Given i and x, change A[i] to x, 0 &lt;= i &lt;= n-1. Examples: Input: a[] = {2, 6, 7, 5, 18, 86, 54, 2} Query1: maximum(
14 min read
Multiplication on Array : Range update query in O(1)
Consider an array A[] of integers and the following two types of queries. update(l, r, x): multiply x to all values from A[l] to A[r] (both inclusive).printArray(): Prints the current modified array. Examples: Input: A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} update(0, 2, 2) update(1, 4, 3) print() update(4, 8, 5) print() Output: 2 6 6 3 15 5 5 5 5 1 Exp
7 min read
Difference Array | Range update query in O(1)
Consider an array A[] of integers and following two types of queries. update(l, r, x) : Adds x to all values from A[l] to A[r] (both inclusive).printArray() : Prints the current modified array. Examples : Input : A [] { 10, 5, 20, 40 } update(0, 1, 10) printArray() update(1, 3, 20) update(2, 2, 30) printArray() Output : 20 15 20 40 20 35 70 60 Expl
8 min read
Binary Indexed Tree : Range Update and Range Queries
Given an array arr[0..N-1]. The following operations need to be performed. update(l, r, val): Add ‘val’ to all the elements in the array from [l, r].getRangeSum(l, r): Find the sum of all elements in the array from [l, r].Initially, all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before range sum. E
15+ min read
Probability of cutting a rope into three pieces such that the sides form a triangle
Given a rope. We have to find the probability of cutting a rope into 3 pieces such that they form a triangle. Answer: 0.25 Explanation: Let the length of rope be 1 unit. We choose two points X and Y on the rope. Note: Formation of triangle is based on Triangle inequality i.e. sum of the lengths of any two sides of a triangle must be greater than th
2 min read
Probability that the pieces of a broken stick form a n sided polygon
We have a stick of length L. The stick got broken at (n-1) randomly chosen points (lengths of parts can be non-integer or floating point numbers also) so we get n parts. We need to find the probability that these n pieces can form a n sided polygon. Examples: Input : L = 5 n = 3 Output : 0.25 We need to cut rope of length 5 into three parts. First
4 min read
Maximum number of pieces in N cuts
Given a square piece and a total number of cuts available n, Find out the maximum number of rectangular or square pieces of equal size that can be obtained with n cuts. The allowed cuts are horizontal and vertical cut. Note: Stacking and folding is not allowed.Examples: Input : n = 1 Output : 2 Explanation : Input : n = 2 Output : 4 Explanation : I
5 min read
Maximum length possible by cutting N given woods into at least K pieces
Given an array wood[] of size N, representing the length of N pieces of wood and an integer K, at least K pieces of the same length need to be cut from the given wooden pieces. The task is to find the maximum possible length of these K wooden pieces that can be obtained. Examples: Input: wood[] = {5, 9, 7}, K = 3 Output: 5 Explanation: Cut arr[0] =
8 min read
Print all unique combinations of setting N pieces on an NxN board
Given an integer N, the task is to print all the unique combinations of putting N pieces in an NxN board. Note: Print ("*") for pieces and ("-") for an empty space. Example: Input: N = 2Output:* *- - * -* - * -- * - ** - - *- * - -* *Explanation: The total number of empty spaces are 2*2=4 and the pieces to be set is 2 so there are 4C2 combinations
8 min read
Trap the King by one of the given Set of pieces
Given an 8 X 8 matrix of characters '*' and 'K' as a chessboard in which K represents the position of the King and the rest of the cell is represented by *. Also given the following three sets of pieces: Set 1: 1 QueenSet 2: 1 Queen, 1 RookSet 3: 1 Queen, 1 Rook, 1 Bishop Then you have to trap the King in such a way that all conditions should be me
15+ min read
Number of ways to cut a stick of length N into in even length at most K units long pieces
Given a rod of length N units, the task is to find the number of ways to cut the rod into parts such that the length of each part is even and each part is at most K units. Examples: Input: N = 6, K = 4 Output: 3 Explanation: Rod of length 6 units needs to be into parts having length at most 4 units. Hence cut the rod in three ways: Way 1: 2 units +
9 min read
Number of ways to cut a stick of length N into K pieces
Given a stick of size N, find the number of ways in which it can be cut into K pieces such that length of every piece is greater than 0. Examples : Input : N = 5 K = 2 Output : 4 Input : N = 15 K = 5 Output : 1001 Solving this question is equivalent to solving the mathematics equation x1 + x2 + ..... + xK = N We can solve this by using the bars and
8 min read
Segment Tree for Range Addition and Range Minimum Query
Given an array of size N initially filled with 0s. There are Q queries to be performed, and each query can be one of two types: Type 1 (1, L, R, X): Add X to all elements in the segment from L to R−1.Type 2 (2, L, R): Find the minimum value in the segment from L to R−1.Example: Input: n = 5, q = 6, queries = { {1, 0, 3, 3}, {2, 1, 2}, {1, 1, 4, 4},
15+ min read
Mo's Algo with update and without update
Mo's Algorithm is a truly versatile algorithm that finds utility in a vast array of problems requiring querying an array or a list for a subarray. Now, let me tell you, this algorithm owes its efficiency to a very specific order of processing the queries, which significantly reduces the time required to access the array elements. How does Mo's Algo
15+ min read
Range Minimum Query with Range Assignment
There is an array of n elements, initially filled with zeros. The task is to perform q queries from given queries[][] and there are two types of queries: Type 1 (i.e queries[i][0] == 1): Assign value val = queries[i][3] to all elements on the segment l = queries[i][1] to r = queries[i][2].Type 2 (i.e queries[i][0] == 2): Find the minimum on the seg
15+ min read
Update and Print for all the Query
Given an array arr[] of length N consisting of a positive integer, the task is to complete the Q queries and print values accordingly which consists of two types of operations: Operation 1: Update all the indices of the array to its digit sum which lies under the range L and R(0 ? L, R ? N-1).Operation 2: Print the value of the array at that index.
15+ min read
Sum of odd Array elements after each update query
Given an integer array Arr[] of length N and an array Queries[] of length Q where Queries[i] = [valuei, indexi]. For each query i, update Arr[indexi] = Arr[indexi] + valuei, then print the sum of the all the odd values of Arr[]. Examples: Input: N = 4, Arr = [1,2,3,5], Q = 4, Queries = [[1,0],[-3,1],[-4,0],[2,3]]Output: 8 7 7 9Explanation: At the b
15+ min read
Find element which maximize the XOR value for N given update query
Given arrays Arr[] and Queries[] of size N and an integer K such that (0 â‰Ī Arr[i], Queries[i] &lt; 2K), the task is to form an array, where each element represents an integer such that XOR of all elements of array and element is maximum by updating Arr[i] with Queries[i] at each step (0 â‰Ī i â‰Ī N-1). Examples: Input: N = 4, Arr[] = {2, 3, 4, 7}, Quer
8 min read
CSES Solutions - Chessboard and Queens
Your task is to place eight queens on a chessboard so that no two queens are attacking each other. As an additional challenge, each square is either free or reserved, and you can only place queens on the free squares. However, the reserved squares do not prevent queens from attacking each other. How many possible ways are there to place the queens?
7 min read
Save from Bishop in chessboard
You are given a 8*8 chess board. Along with the chess board there is a Bishop placed on board and its position is known. Position of Bishop is given in form of two digit integer where both digits are greater than 0 and less than 9 (like 67 denotes 6th column and 7th row). Now your task is to find the number of ways in which you can place a pawn saf
6 min read
Check if a king can move a valid move or not when N nights are there in a modified chessboard
Given an infinite chessboard with the same rules as that of chess. Also given are N knights coordinates on the infinite chessboard(-10^9 &lt;= x, y &lt;= 10^9) and the king's coordinate, the task is to check if the King is checkmate or not. Examples: Input: a[] = { {1, 0}, {0, 2}, {2, 5}, {4, 4}, {5, 0}, {6, 2} } king -&gt; {3, 2} Output: Yes The k
10 min read
Count of squares reachable by a Bishop initially placed at top left on a given NxM chessboard
Given two integers N and M representing a N x M chessboard, the task is to find the maximum number of squares that the bishop can reach using any number of moves if initially it is placed in the top left corner of the chessboard. Examples: Input: N = 8, M = 8Output: 32Explanation: The bishop is initially standing on (1, 1) which is either a white o
4 min read
Maximum bishops that can be placed on N*N chessboard
Given an integer n, the task is to print the maximum number of bishops that can be placed on a n x n chessboard so that no two bishops attack each other. For example, maximum 2 bishops can be placed safely on 2 x 2 chessboard. Examples: Input: n = 2 Output: 2 We can place two bishop in a row. Input: n = 5 Output: 8 Approach: A bishop can travel in
11 min read
Ways to place K bishops on an N×N chessboard so that no two attack
Given two integers N and K, the task is to find the number of ways to place K bishops on an N × N chessboard so that no two bishops attack each other. Here is an example for a 5×5 chessboard. Examples: Input: N = 2, K = 2 Output: 4 The different ways to place 2 bishops in a 2 * 2 chessboard are : Input: N = 4, K = 3 Output: 232 Approach: This probl
10 min read
Check if the given chessboard is valid or not
Given an NXN chessboard. The task is to check if the given chessboard is valid or not. A chess board is considered valid if every 2 adjacent cells are painted with different color. Two cells are considered adjacent if they share a boundary. First chessboard is valid whereas the second is invalid. Examples: Input : N = 2 C = { { 1, 0 }, { 0, 1 } } O
10 min read
Number of blocks in a chessboard a knight can move to in exactly k moves
Given integers i, j, k and n where (i, j) is the initial position of the Knight on a n * n chessboard, the task is to find the number of positions the Knight can move to in exactly k moves.Examples: Input: i = 5, j = 5, k = 1, n = 10 Output: 8Input: i = 0, j = 0, k = 2, n = 10 Output: 10 The knight can see total 10 different positions in 2nd move.
8 min read
Total position where king can reach on a chessboard in exactly M moves
Given an integer M, an 8 * 8 chessboard and the king is placed on one of the square of the chessboard. Let the coordinate of the king be (R, C). Note that the king can move to a square whose coordinate is (R1, C1) if and only if below condition is satisfied. The task is to count the number of position where the king can reach (excluding the initial
7 min read