Given ‘n’ line segments, each of them is either horizontal or vertical, find the maximum number of triangles(including triangles with zero area) that can be formed by joining the intersection points of the line segments.
No two horizontal line segments overlap, nor do two vertical line segments. A line is represented using two points(four integers, first two being the x and y coordinates, respectively for the first point and the other two being the x and y coordinates for the second point)
| ---|-------|-- | | ----- | --|--|- | | | | For the above line segments, there are four points of intersection between vertical and horizontal lines, every three out of which form a triangle, so there can be 4C3 triangles.
The idea is based on Sweep Line Algorithm.
Building a solution in steps:
- Store both points of all line segments with the corresponding event(described below) in a vector and sort all the points, in non-decreasing order of their x coordinates.
- Let’s now imagine a vertical line that we sweep across all these points and describe 3 events, based on which point we currently are:
- in – leftmost point of a horizontal line segment
- out – rightmost point of a horizontal line segment
- a vertical line
- We call the region “active” or the horizontal lines “active” that have had the first event but not second. We will have a BIT(Binary indexed tree) to store the ‘y’ coordinates of all active lines.
- Once a line becomes inactive, we remove its ‘y’ from the BIT.
- When an event of third type occurs, that is, when we are at a vertical line, we query the tree in range of its ‘y’ coordinates and add the result to the number of intersection points so far.
- Finally, we will have the number of points of intersections, say m, then the number of triangles (including zero area) will be mC3.
Note: We need to carefully sort the points, look at the cmp() function in the implementation for clarification.
Number of triangles are: 4
Time Complexity: O( n * log(n) + n * log(maximum_y) )
This article is contributed by Saumye Malhotra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.