CP Notebook

← all snippets

InsidePolygon

Returns true if p lies within the polygon. If strict is true, it returns false for points on the boundary. The algorithm uses products in intermediate steps so watch out for overflow.

Time: O(n) 11 lines stress-tested and tested on kattis:pointinpolygon

Usage: vector<P> v = P4,4, P1,2, P2,1; bool in = inPolygon(v, P3, 3, false);

Needs: "Point.h", "OnSegment.h", "SegmentDistance.h"

content/geometry/InsidePolygon.h — Victor Lecomte, chilli, source: https://vlecomte.github.io/cp-geo.pdf

template<class P>
bool inPolygon(vector<P> &p, P a, bool strict = true) {
	int cnt = 0, n = sz(p);
	rep(i,0,n) {
		P q = p[(i + 1) % n];
		if (onSegment(p[i], q, a)) return !strict;
		//or: if (segDist(p[i], q, a) <= eps) return !strict;
		cnt ^= ((a.y<p[i].y) - (a.y<q.y)) * a.cross(p[i], q) > 0;
	}
	return cnt;
}