Five problems rated 2,200 to 2,400 about points, polygons and segments. The move: decide every question with the sign of an integer cross product, and sort so that one sweep or one search does the rest.
Each problem in this tent asks a question about points on a plane. Is an address inside a zone, what is the shortest fence, which two riders are nearest, how much of a page is covered, how many corridors cross aisles.
The table shows the question, and the sweep or search that answers it quickly.
| Problem | The question | What answers it quickly |
|---|---|---|
| Is the address inside the delivery zone | inside, on the border or outside a convex polygon | cross product signs and a binary search for the wedge |
| The shortest fence around charging stations | the convex hull and its area | sort, then a stack that pops non-left turns |
| Pooling the two closest riders | the nearest pair of points | split on x, and check a strip sorted by y |
| How much of the page do the banners cover | the area of a union of rectangles | sweep over x with a segment tree of covered height |
| Where corridors meet aisles on a warehouse plan | the number of crossings | sweep over x with a Fenwick tree of open aisles |
All five use the same primitive. The cross product of two vectors says which way you turn, and in whole numbers it is exact.
Here is the hull of six points. The code sorts the points, builds a lower chain and an upper chain, and prints the number of corners and twice the area.
Exercise · Predict the output: The corners of the fence. The six points are the four corners of a square of side 2, one point on the middle of its bottom edge, and one point in the middle. The code pops the last point while the turn is not strictly left. What does it print: the number of corners and twice the area?
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def chain(points):
part = []
for p in points:
while len(part) >= 2 and cross(part[-2], part[-1], p) <= 0:
part.pop()
part.append(p)
return part
pts = [(0, 0), (0, 2), (1, 0), (1, 1), (2, 0), (2, 2)]
hull = chain(pts)[:-1] + chain(pts[::-1])[:-1]
twice = 0
for i in range(len(hull)):
x1, y1 = hull[i]
x2, y2 = hull[(i + 1) % len(hull)]
twice += x1 * y2 - x2 * y1
print(len(hull), abs(twice))The move has two parts.
First, decide every geometric question with the cross product of two vectors from a common point o. For the points o, a and b it is (a.x - o.x) × (b.y - o.y) - (a.y - o.y) × (b.x - o.x). A positive value means b is to the left of the line from o to a. A negative value means to the right, and zero means the three points lie on one line.
Second, sort so that each decision looks only at the nearest points. Sorting by x turns a hull into two walks with a stack. It turns the closest pair into a split down the middle, and it turns areas and crossings into a sweep that moves along x.
The sign of an integer cross product is exact. After sorting, each decision needs only the points next to the current one. These are the top of a stack, a strip near a line, or the shapes open at the current x.
Because there are no divisions and no angles, there are no rounding errors. A point exactly on a border gives exactly 0, and that is a case you decide on purpose.
The cross product of two vectors is positive for a left turn, negative for a right turn, and zero on a line.
Whether collinear points stay or go is one character in the test.
Exercise · Find the bug: The point that stays on an edge. This returns the number of corners of the shortest fence around distinct points. It builds a lower and an upper chain with a stack. It returns too many on some inputs. Which line is wrong?
def hull_size(points):
n = len(points)
if n == 1:
return 1
pts = sorted(points)
chain = [None] * (2 * n)
size = 0
for sweep in range(2):
start = size
for i in range(n):
p = pts[i] if sweep == 0 else pts[n - 1 - i]
while size - start >= 2:
o, a = chain[size - 2], chain[size - 1]
cross = (a[0] - o[0]) * (p[1] - o[1]) - (a[1] - o[1]) * (p[0] - o[0])
if cross < 0:
size -= 1
else:
break
chain[size] = p
size += 1
size -= 1
return sizeThe Academy lessons Comparators and Merge sort and inversions gave you sorting by a custom key and counting across two halves. Lower and upper bound gave you binary search, and Range queries gave you the Fenwick and segment trees. This tent changes three things.
Sorting becomes a sweep. After sorting by x, a line moves along the plane and a structure holds the shapes that are open at the current x. The union of banners uses a segment tree of covered height. The crossings use a Fenwick tree of open aisles by height.
Degenerate cases decide the answer. Collinear points, duplicate points and segments that touch at an end all give a cross product of 0, and a wrong choice there fails some test. The order at one x is open, ask, close, so touching shapes meet.
The numbers are large. With coordinates up to 10^6, a cross product reaches 8 × 10^12, far above 2^31, which is 2,147,483,648. Squared distances and twice an area need 64 bits too.
The speed-ups are large as well. For 100,000 addresses and a zone of 20,000 corners, one test per corner is 2,000,000,000 steps, and a binary search is 1,500,000. For 100,000 riders there are 4,999,950,000 pairs, and a split down the middle takes about 1,660,964 steps. For 30,000 banners on a page of 10^6 by 10^6, counting unit squares is 10^12 steps, and the sweep takes about 952,360.
After sorting by x, the closest pair need not be neighbours. Check the strip near the middle line in y order.
After sorting by x, the closest pair is not always a neighbour in that order.
Exercise · Break it: The nearest point in the sorted list. This returns the smallest squared distance between two points. It sorts the points by x, then by y, and compares only points that are next to each other in that order. Find an input where it is wrong.
def closest_squared(points):
pts = sorted(points)
best = None
for i in range(1, len(pts)):
dx = pts[i][0] - pts[i - 1][0]
dy = pts[i][1] - pts[i - 1][1]
d = dx * dx + dy * dy
if best is None or d < best:
best = d
return bestThe limits tell you which sweep to use, and which numbers need 64 bits.
| Limit | What it tells you |
|---|---|
| 20,000 corners, 100,000 addresses | O(q log n): 1,500,000 steps by binary search |
| 100,000 points | sort, then a stack, or split on x: n log n |
| 30,000 banners | events by x with a segment tree: about 950,000 steps |
| coordinates up to 10^6 | cross products up to 8 × 10^12: use 64-bit integers |
| collinear points and shared ends | decide them on purpose: test with zero cross products |
The full treatment is in Fast I/O and stress testing. The first line holds the number of points n, and each of the next lines holds the two coordinates of a point. The program reads them all at once and prints twice the area of the polygon in the order given, using the shoelace sum in 64 bits.
It was run on the rectangle with the corners (0,0), (4,0), (4,3) and (0,3), which prints 24. On the square with corners at plus and minus 1,000,000 it prints 8,000,000,000,000.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
xs = [int(data[1 + 2 * i]) for i in range(n)]
ys = [int(data[2 + 2 * i]) for i in range(n)]
twice = 0
for i in range(n):
j = (i + 1) % n
twice += xs[i] * ys[j] - xs[j] * ys[i]
sys.stdout.write(str(abs(twice)) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] xs = new long[n], ys = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
xs[i] = (long) in.nval;
in.nextToken();
ys[i] = (long) in.nval;
}
long twice = 0;
for (int i = 0; i < n; i++) {
int j = (i + 1) % n;
twice += xs[i] * ys[j] - xs[j] * ys[i];
}
System.out.println(Math.abs(twice));
}
}#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> xs(n), ys(n);
for (int i = 0; i < n; i++) cin >> xs[i] >> ys[i];
long long twice = 0;
for (int i = 0; i < n; i++) {
int j = (i + 1) % n;
twice += xs[i] * ys[j] - xs[j] * ys[i];
}
cout << llabs(twice) << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
let twice = 0;
for (let i = 0; i < n; i++) {
const j = (i + 1) % n;
twice += data[1 + 2 * i] * data[2 + 2 * j] - data[1 + 2 * j] * data[2 + 2 * i];
}
process.stdout.write(String(Math.abs(twice)) + "\n");Geometry bugs hide in degenerate cases. Use a small grid of coordinates, so that equal x values, equal points and collinear triples come up often. Compare the fast code with the brute force.
import random
from fast import closest_pair_squared
from slow import closest_pair_squared as slow_closest
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(2, 9)
riders = [[rng.randint(-5, 5), rng.randint(-5, 5)] for _ in range(n)]
if closest_pair_squared([r[:] for r in riders]) != slow_closest([r[:] for r in riders]):
print("different at seed", seed, riders)
break
else:
print("all 1000 inputs agree")On the divide and conquer solution it printed all 1000 inputs agree. With only the neighbours in the sorted list compared, it stops at seed 16.
Problems rated 2,200 to 2,400 are standard ideas with sharp edges. Write the sign test first, list the degenerate cases, and keep 15 minutes for a stress test on a small grid.
The ratings go 2,200, 2,300, 2,400, 2,400 and 2,400. The first two use the sign of a cross product with a binary search and a stack. The closest pair splits on x. The last two sweep along x with a tree.
For each problem, write two lines before you code: which cross product sign decides, and what the sort or the sweep keeps. Then list the degenerate cases: collinear points, equal points and shared ends.
Checkpoint · Geometry basics
Q1/5 The cross product of the vectors o to a and o to b is 0. What does that say about the three points?
Answer: C
A positive value is a left turn and a negative value is a right turn. Zero means no turn at all, so the three points are collinear.
Q2/5 A convex hull is built with a stack that pops while the cross product is less than or equal to 0. What happens to a point that lies exactly on an edge between two corners?
Answer: B
The turn at such a point is exactly 0. With strict popping only for negative values, the point stays and the hull for the points (0,0), (1,0), (2,0), (2,2), (0,2) has 5 corners instead of 4.
Q3/5 Points (0,0), (0,10) and (1,0) are sorted by x and then y. Why does comparing only neighbours in that order give the wrong closest pair?
Answer: B
Sorting by x only puts points of a vertical strip next to each other. The nearest pair can be two points with very different positions in the sorted list. The strip must be checked in y order.
Q4/5 Coordinates go up to 10^6 in absolute value. About how large can a cross product be, and what type do you need?
Answer: C
Each difference is up to 2 × 10^6, and the cross product is a difference of two products of such numbers, so it reaches 8 × 10^12. That is far above 2^31, which is 2,147,483,648.
Q5/5 A sweep over x has an aisle that ends at x = 5 and a corridor at x = 5. In what order should the three kinds of event at one x be processed?
Answer: C
Shapes that touch at one x still meet. Opening first and closing last lets the corridor at x = 5 see the aisle that ends there and the aisle that starts there.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.