---
id: 2307
lang: en
translation_of: index.md
source_sha256: d7f4d45dc1e0bf2871374746c958becdf0fb80b6bf245223cafbc903e9511e8e
title: "Computational Geometry"
description: "Computational geometry problems in contests are usually not hard, but if you have never learned it you just score zero."
tags: ["OI","Computational Geometry"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Alt text of the second image is the macOS screenshot filename 截屏2020-05-05 上午9.22.32; rendered as “Screenshot 2020-05-05 9.22.32 AM”. The first image's alt (a numeric filename) is unchanged."
  - "判段 in the point-line distance paragraph is read as a typo for 判断 (check), and 然后在用 as 然后再用 (then use)."
  - "快速排斥实验和跨立实验 rendered with the usual English names, “rapid rejection test and straddle test”, treated as jargon."
---

## Overview

Computational geometry problems you run into in contests are usually not hard, but if you run into one without having learned it, you just <span class="slang" data-zh="爆零" data-gloss="bàolíng, “explode to zero”. Scoring zero points on a problem or contest.">score zero</span>. To avoid that, I decided to properly learn some computational geometry.

Result: I learned it all and still <span class="slang" data-zh="爆零" data-gloss="bàolíng, “explode to zero”. Scoring zero points on a problem or contest.">scored zero</span>.

<!--more-->

## Vector <span class="slang" data-zh="全家桶" data-gloss="quánjiātǒng, “family bucket”, as in a fast-food family meal. A bundle with the whole set of something.">Combo Meal</span>

There's nothing much to say about the normal vector stuff, so I'll just talk about what the cross product means. The cross product is the signed area of the parallelogram enclosed by the two vectors. The picture makes it clear:

![1451707-20181015165912609-1583781832](media/1451707-20181015165912609-1583781832.jpg)

The code:

```cpp
struct vec
{
    double x, y;
    vec(double _x = 0, double _y = 0) : x(_x), y(_y) {}
    vec operator+(const vec &rhs) { return vec(x + rhs.x, y + rhs.y); }
    vec operator-(const vec &rhs) { return vec(x - rhs.x, y - rhs.y); }
    double operator*(const vec &rhs) const { return x * rhs.x + y * rhs.y; }
    vec operator*(const double &rhs) { return vec(x * rhs, y * rhs); }
    double operator^(const vec &rhs) const { return x * rhs.y - y * rhs.x; }
    vec operator/(const double &rhs) const { return vec(x / rhs, y / rhs); }
    double len2() { return x * x + y * y; }
    double len() { return sqrt(len2()); }
    vec normalize() { return (*this) / len(); }
};
```

## Points, Lines

**Position of a point relative to a line**

If we want to tell whether point $P$ is to the left or the right of a line with direction vector $v$, we can pick a point $Q$ on the line and then just check the sign of $\vec{QP} \times v$.

**Checking whether segments intersect**

First deal with parallel segments, which you can do by checking the cross product twice. If they overlap, check whether there are three collinear points (you can also use the cross product to check the angle). Once that's settled, we properly check whether they intersect.

First check whether the quadrilateral regions occupied by the two segments overlap. If they do, check further: you can use the point-line position test above to see whether the two endpoints of one segment lie on opposite sides of the other segment. Combine the two and you're done. These are called the rapid rejection test and the straddle test.

**Intersection point of two lines**

Let me draw a picture:

![Screenshot 2020-05-05 9.22.32 AM](media/截屏2020-05-05-上午9.22.32.png)

If we want point G, since we know the coordinates of point $B$, we can try to find $\vec{BG}$ and then just add them. Finding $\vec{BG}$ isn't hard: think of computing it directly as $\vec{BG} = \vec{u} \times \frac{|\vec{BG}|}{|\vec{u}|}$. Notice there's a ratio-like thing at the end; we can express it with vector cross products, because with the same base, the ratio of areas means the ratio of heights.

```cpp
vec intersect(vec a, vec b, vec c, vec d)
{
    vec v = b - a, w = d - c, u = a - c;
    return a + v * double((w ^ u) / (v ^ w));
}
```

**Intersection point of two segments**

First run the intersection check, then just handle it with the method for the intersection of two lines.

**Point-line distance**

If it's a segment, you first have to check the lengths to the two endpoints. Computing the point-line distance really just means finding the area of the parallelogram and then dividing by the base.

## Polygons

**Convex hull**

Sort by the $x$-axis first, then just maintain a monotonic stack where the cross products are monotonic.

```cpp
// P2742.cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#define pr pair<double, double>
using namespace std;
int n;
vector<pr> points;
deque<int> prs;
double getDist(pr a, pr b)
{
    return sqrt((a.first - b.first) * (a.first - b.first) + (a.second - b.second) * (a.second - b.second));
}
bool judge(int a, int b, int idx)
{
    return (points[a].second - points[b].second) * (points[b].first - points[idx].first) >
           (points[a].first - points[b].first) * (points[b].second - points[idx].second);
}
int main()
{
    double ans = 0;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        double x, y;
        scanf("%lf%lf", &x, &y);
        points.push_back(make_pair(x, y));
    }
    sort(points.begin(), points.end());
    prs.push_front(0), prs.push_front(1);
    for (int i = 2; i < n; i++)
    {
        while (prs.size() > 1 && !judge(prs[0], prs[1], i))
            prs.pop_front();
        prs.push_front(i);
    }
    for (int i = 0; i < prs.size() - 1; i++)
        ans += getDist(points[prs[i]], points[prs[i + 1]]);
    prs.clear();
    prs.push_front(0), prs.push_front(1);
    for (int i = 2; i < n; i++)
    {
        while (prs.size() > 1 && judge(prs[0], prs[1], i))
            prs.pop_front();
        prs.push_front(i);
    }
    for (int i = 0; i < prs.size() - 1; i++)
        ans += getDist(points[prs[i]], points[prs[i + 1]]);
    printf("%.2lf", ans);
    return 0;
}
```

**Checking whether a point lies inside a convex polygon**

Odd inside, even outside. [https://www.cnblogs.com/anningwang/p/7581545.html](https://www.cnblogs.com/anningwang/p/7581545.html)

**Area of a convex polygon**

This one is fairly simple, just:

$$
S = \frac{1}{2} \sum_{i = 1}^{n - 1} P_i \times P_{i + 1} i
$$

## Half-Plane Intersection

## Rotating Calipers
