Chapter 117
HomeComputational geometry starts with points and vectors. The dot product gives projection; the cross product gives orientation and area. These are the building blocks for everything else.
struct Point { double x, y; };
using Vec = Point;
double dot(Vec a, Vec b) { return a.x * b.x + a.y * b.y; }
double cross(Vec a, Vec b) { return a.x * b.y - a.y * b.x; }
double norm2(Vec a) { return a.x * a.x + a.y * a.y; }
double norm(Vec a) { return sqrt(norm2(a)); }
// Orientation of (a,b,c): cross(b-a, c-a)
// > 0: counter-clockwise, < 0: clockwise, = 0: collinear
double orient(Point a, Point b, Point c) {
return cross({b.x - a.x, b.y - a.y}, {c.x - a.x, c.y - a.y});
}
// Distance from point c to line (a,b)
double dist_to_line(Point a, Point b, Point c) {
return abs(cross({b.x - a.x, b.y - a.y}, {c.x - a.x, c.y - a.y}))
/ sqrt(norm2({b.x - a.x, b.y - a.y}));
}💡 Use long long for integer coordinates
Many CP geometry problems use integer coordinates. Use long long and avoid floating point where possible. Cross product of 64-bit ints fits in 128 bits — use __int128 in C++.