Given x coordinates of N vertical lines (parallel to Y-axis) and M line segments extending from (x1, y1) to (x2, y2), the task is to find the total number of intersections of the line segments with the vertical lines.
Examples:
Input:_ N = 2, M = 1, lines[] = {-1, 1}, Segments[][4] = {0, 1, 2, 1}_
Output:_ 1_
Explanation:
There is only one point of intersection (1, 1)
Input:_ N = 4, M = 8, lines[] = {-5, -3, 2, 3}, segments[][4] = {{-2, 5, 5, -6}, {-5, -2, -3, -5}, {-2, 3, -6, 1}, {-1, -3, 4, 2}, { 2, 5, 2, 1}, { 4, 5, 4, -5}, {-2, -4, 5, 3}, { 1, 2, -2, 1}};_
Output:_ 8_
Explanation:
There are total of 8 intersections.
Dotted lines are the vertical lines.
A green circle denote a single point of intersection and
a green triangle denotes that two line segments
intersect same vertical line at that point.
Naive Approach:
The simplest approach is, for each query, check if a vertical line falls between the x-coordinates of the two points. Thus, each segment will have O(N) computational complexity.
Time complexity:_ O(N * M)_
Approach 2: The idea is to use Prefix Sum to solve this problem efficiently. Follow the steps below to solve the problem:
Below is the implementation of the above approach.
#arrays #competitive programming #geometric #hash #cpp-map #geometric-lines