Ninja lives in the village and has animal husbandry which consists of various animals like cows, sheep, etc. Ninjas’ village also has animal-eating monsters which eat animals that are not present in the fence of the husbandry. You have given the points array ‘POINTS’ having ‘N’ vertices which denote the coordinates in the X-Y plane of the fence and the coordinates of the animal ‘X’ and ‘Y’. The width of the fence is very large so the points present on the fence are considered to be inside. Find if the given animal is safe from monsters or not.
The first line of input contains an integer ‘T’, the number of test cases.
The first line of each test case contains a single integer ‘N’, representing the number vertices of the fence.
The next ‘N’ lines will denote the coordinates of the fence in the X-Y place.
The ‘N + 1’th line will denote the coordinates of the animal in the X-Y plane.
Output Format :
For each test case, return a single integer ‘1’ if the animal is safe, else print ‘0’.
Print output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 2*10^3
-10^4 <= X, Y <= 10^4
Time Limit: 1 sec
1
4
0 0
0 1
1 0
1 1
2 0
0
The fencing and animal in the X-Y plane will be :
As the animal is outside of the fence, so it is not safe.
1
3
0 0
5 0
5 5
3 3
1
Think of an approach using the intersection of line segments.
The basic idea is to make a horizontal line to the right of each point by extending it. We count the number of times the animal line segment intersects with the fence line segment. If the intersection is an odd number of times then the point lies in the circle, else it lies outside the circle.
Special case: When the coordinates of the animal are colinear with line segments of the fences, we check whether that point lies on the segment or not. If it lies on the segment it is considered to be inside the fence
Here is the algorithm :
INTERSECT(‘F1’, ‘F2, ‘A1’, ‘A2’) (Function to find the intersection of line segments.)
ORIENTATION(‘P’, ‘Q’, ‘R’) (Function to find the orientation.)
onLine(‘P’, ‘Q’, ‘R’) (Function to check whether a point lies on the line or not.)
O(N), where ‘N’ is the number of vertices of the fence.
We traverse all the vertices of the fence to find the intersection. Therefore, the overall time complexity will be O(N).
O(1)
We don’t use any extra space. Therefore, the overall space complexity will be O(1).