![]() |
VOOZH | about |
Given N pieces of chessboard all being 'white' and a number of queries Q. There are two types of queries :
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 :
Naive Approach :
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
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