CP Notebook

← all snippets

PolygonCenter

Returns the center of mass for a polygon.

Time: O(n) 9 lines Tested

Needs: "Point.h"

content/geometry/PolygonCenter.h — Ulf Lundstrom

typedef Point<double> P;
P polygonCenter(const vector<P>& v) {
	P res(0, 0); double A = 0;
	for (int i = 0, j = sz(v) - 1; i < sz(v); j = i++) {
		res = res + (v[i] + v[j]) * v[j].cross(v[i]);
		A += v[j].cross(v[i]);
	}
	return res / A / 3;
}