You are on page 1of 2

7/27/2020 LAZER - Editorial - editorial - CodeChef Discuss

LAZER - Editorial
binary-indexed-tree, easy-medium, editorial, segment-tree, march20, tmwilliamlin, sweep-line

tmwilliamlin #1 March 20, 2020, 7:19pm

PROBLEM LINK:
Practice
Div-2 Contest
Div-1 Contest

Author: Vivek Chauhan


Tester: Suchan Park
Editorialist: William Lin

DIFFICULTY:
Easy-Medium

PREREQUISITES:
Sweep Line, Binary Indexed Tree, Segment Tree

PROBLEM:
There are N points, the i-th point is at (i, A_i). For all 0\le i \le N-2, segment i connects points i and
i+1. You are given Q queries (l, r, y), meaning that you need to calculate the number of segments in
[l, r) that intersect with the horizontal line with height y.

QUICK EXPLANATION:
Segment i will intersect with the line if \min(A_i, A_{i+1})\le y \le \max(A_i, A_{i+1}). We will sweep
over y while maintaining the segments that could be intersected in a data structure while answer
queries.

EXPLANATION:
Segment i will be active if it intersects with the horizontal line at y for some query (even if the
segment is not within [l, r)). Let the value of a segment be 1 if it is active and 0 if it is inactive. The
values of the segments are represented by the array v shown below:

https://discuss.codechef.com/t/lazer-editorial/57553/print 1/7
7/27/2020 LAZER - Editorial - editorial - CodeChef Discuss

The answer for a query is the number of active segments in [l, r), or the sum of the values of the
segments in [l, r). In order to answer the queries e ciently, we will use a sweepline algorithm. The
idea of this sweepline algorithm is to imagine a horizontal line sweeping from y=-\infty to y=\infty.
At any point in time, the values of the segments should be updated for the current horizontal line.
Whenever the horizontal line reaches y_i for some query i, we will answer query i.

There are three types of events:

1. For each segment i, when the line reaches y=\min(A_i, A_{i+1}), the value of the segment i will
become 1.
2. For each query i, when the line reaches y_i, we will answer query i by adding up the values of
the segments in [l, r).
3. For each segment i, when the line goes over y=\max(A_i, A_{i+1}), the value of the segment i
will become 0.

Since the sweepline starts from y=-\infty and moves to y=\infty, we should process the events in
increasing order of y. The only thing which remains is to calculate the sum of the values of the
segments in [l, r) e ciently for each query. This can be done with any data structure which
supports 1. update x_i=v, given i and v 2. nd the sum of x_i in a given range. A binary indexed tree
or a segment tree will work.

The total time complexity is O(N \log N).

SOLUTIONS:
Setter's Solution
Tester's Solution
Editorialist's Solution

Please give me suggestions if anything is unclear so that I can improve. Thanks

14 Likes

https://discuss.codechef.com/t/lazer-editorial/57553/print 2/7

You might also like