Advertisement
flash_7

Point Inside a Convex Polygon

Mar 2nd, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Point{
  5.     double x, y;
  6. };
  7.  
  8. /// Compute A X B:
  9. int cross(Point A, Point B){
  10.     return (A.x * B.y - A.y * B.x);
  11. }
  12.  
  13. /// Compute the cross product AB X AC
  14. int crossProduct(Point A, Point B, Point C) {
  15.     Point AB = {B.x - A.x, B.y - A.y}; /// AB vector
  16.     Point AC = {C.x - A.x, C.y - A.y}; /// AC vector
  17.     return cross(AB, AC);
  18. }
  19.  
  20. bool isLeft(Point A, Point B, Point C){
  21.     if(crossProduct(A, B, C) >= 0) return true;
  22.     return false;
  23. }
  24.  
  25. /// The point lie inside the triangle only if,
  26. /// the point is at the same side of each of the side of that triangle.
  27. bool insideTriangle(Point A, Point B, Point C, Point P){
  28.     if(isLeft(P,A,B) == isLeft(P,B,C) && isLeft(P,B,C) == isLeft(P,C,A)) return true;
  29.     return false;
  30. }
  31.  
  32. /// Find the immediate close point who is at the right side of (List[0] - P) vector.
  33. int bSearch(int N, Point P, vector<Point> &List){
  34.     int L = 1, R = N-1;
  35.     while (L < R){
  36.         int M = (L+R)/2;
  37.         if (isLeft(List[0], List[M], P)) L = M;
  38.         else R = M - 1;
  39.     }
  40.     return L;
  41. }
  42.  
  43. bool isInside(int N, Point P, vector<Point> &List){
  44.     int pos = bSearch(N, P, List);
  45.     /// List[0] is the lower left most point:
  46.     return insideTriangle(List[0], List[pos], List[pos+1], P);
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement