Editorial
Let and be the numbers of points on the two sides of the line . If all three vertices of a triangle lie on the same side, the triangle is disjoint from and has Type 4. There are such triangles.
Now consider a triangle with vertices on both sides. Let be its only vertex on one side, and let be the two vertices on the other side. Classify the position where the line intersects the line as follows.
- : the intersection is before .
- : the intersection is in the interior of the segment .
- : the intersection is after .
Classify in the same way. These two intersections are the endpoints of the interval where the triangle meets the line . Consequently, the pair of labels determines the type of the triangle.
- : Type 1.
- or : Type 2.
- : Type 3.
- or : Type 4.
For a fixed , let be the numbers of points on the opposite side with labels , respectively. The triangles for which is the unique vertex on its side contribute the following amounts to the four types:
Every triangle having vertices on both sides has a unique vertex on the minority side. Therefore, summing these values over all counts every such triangle exactly once.
It remains to compute efficiently. Apply an affine change of coordinates and regard and . For a point , define
The general-position condition guarantees that every is nonzero and that no ties occur in either ordering.
If is above the line , then
where ranges only over points on the side opposite to . If is below the line, both inequalities are reversed. Thus, sorting all points by and scanning prefix counts for the two sides gives every . A second sort by gives every . Finally,
No division or floating-point arithmetic is needed. Let . For a base point equal to or , sorting the following fraction gives the order of or , respectively:
If the denominator is negative, negate both the numerator and denominator. Compare two fractions by cross multiplication. Signed 128-bit integers are required for these products under the coordinate bounds.
The two sorts take time, and the algorithm uses memory.
Solution written by GPT5