I’m trying to do some SPOJ problem it’s https://www.spoj.pl/problems/FSHEEP/
We have to find out if point is inside the polygon.
As we see it’s not convex polygon ( image from problem ).
I was trying to solve it in O(n*m) time with Ray Casting algorithm described on wikipedia or any other site.
But how to solve it in O(n log m ) ?
So in other words how to check if point is in polygon in logarithmic time?
Since this is a homework-esque problem, I’ll give you homework-esque help.
Rule of thumb: Whenever you see log n, you should think “binary-something” (search, tree, etc). When you see n log n, you should think “sort.” You’ll be surprised how often that works. Can you sort the vertices and binary search on them within your big-O constraints?
UPDATE:
I didn’t want to spoil your fun: You are actually given the polygon vertices in sorted order, so the important sorting was done for you. You don’t need to make an interval in angle-space, use the indexes of the sorted vertex array as your interval.
Cast your ray out from the farmer to the vertex. If it is clockwise, binary search clockwise. If it is anti-clockwise, binary search that direction. The two vertices and the farmer form a bounding triangle. Is the sheep in the bounding triangle?
Crazy lazy pseudocode:
Binary search is O(log m). The triangle check is O(1). Iterating over n sheep gives you O(n)*O(log m)*O(1) = O(n log m).