How to use segment tree and scanline

312 Views Asked by At

Given 300000 segments. Consider any pair of segments: a = [l1,r1] and b = [l2,r2]. If l2 >= l1 and r2 <= r1 , it is "good" pair. If a == b, it is "bad" pair. Overwise, it is "bad" pair.

How to find number of all "good" pairs among given segments using segment tree and scanline?

1

There are 1 best solutions below

0
Daga On

Sort the segments in increasing order with respect to their l-values and for pairs with same l-values sort them in decreasing order with respect to their r-value.

Suppose for a particular , you want to count the number of good pairs (ai,aj) such that j < i. Let ai=[l1,r1] and aj = [l2,r2]. Then we have l2 <= l1. Now we need to count all the possible values of j such that r2 <= r1. This can be done by maintaining a segment tree for the values of r for all j such that 0 < j < i. After querying for the i-th pair, update the segment tree with the r-value of the i-th segment.

Coming to segment tree part, build a segment tree on the values of r. On updating a value of r in segment tree, add 1 to the value of r in the segment tree and for querying for a particular value of r, query for sum in the range [0,r-1]. This will give total number of segments that fit good with the given segment.

If the values of r are big that would not fit into segment tree, then apply coordinate compression to values first and then use segment tree for the compressed values.