问题
I am trying to solve this question, but I am stuck on how to make this work. I will post the question, and then explain where I am in it.
Given a set of horizontal line segments and vertical lines of total size n, we want to compute the number of horizontal segments intersected by each vertical line. The algorithm should be of complexity O(n*logn), and should be achieved by sorting, following by a linear scan. A horizontal segment is specified by two x-coordinates and a y-coordinate, while a vertical line is specified by a single x-coordinate. Output is an array of numbers count[l], one for each vertical line l.
For the sorting, I would think I would sort the entire set by which line finishes earliest (i.e. smallest second x-coordinate, or in the case of a vertical line, just its one x-coordinate) so that I have a linear progression through all of the lines. I am just confused as to how the linear scan following the sorting should be played out. If anyone has any hints, tips, or guidelines, I would appreciate it!
PS: This is practise for a midterm, so while it's not necessarily homework, I will still mark it as such.
回答1:
The question can be written otherwise:
Foreach horizontal segment (x1,x2), find all the vertical lines that intersect it. You can do that by sorting the vertical lines getting a set of position x.
Now, run a binary search and position x1 in the set of x's, let's call its position p1. Do the same for x2, p2. The number of intersection for the given segment equals p2-p1.
Do that for all the horizontal segements.
Sorting the vertical segments will take O(klog(k)). Every search is done in O(log(k)) and is done twice for each segment: O(mlog(k)). Where k is the number of vertical lines and m the number of horizontal segments. n = m+k > m,k therefor, the overall complexity is O(nlogn).
回答2:
First you put all the start/end points of the horizontal segments. and the x-coordinates of the vertical lines, together.
Second, sort them. Let's call the sorted list L
.
Third, imaging there is a vertical scanning line, starting from the left most of your points list L
, moving to the right.
Whenever the scanning line hits a point, it's either a start point of a horizontal segment, or an end point of a horizontal segment, or a vertical line.
And you can do two things when you move the scanning line:
1) keep the set of horizontal segments that the scanning line currently intersects (whenever it's a start/end point of a horizontal segment, add/delete it to/from the set)
2) whenever it's a vertical line, you know that vertical line is intersected by all the horizontal segments in the set you are maintaining by the way in 1)
So, sorting is O(nlogn); moving the scanning line through the sorted list L
is O(n)
All in all, it's O(nlogn)
来源:https://stackoverflow.com/questions/10886975/simple-algorithm-pseudo-code-for-line-segment-intersection