In one of the last stages of the 3rd Universal Cup, there was a not-so-nice problem (it required using fractions) that involved an algorithm for which I hadn't found a tutorial or much information on popular blogs. This approach was developed by me, and I appreciate any feedback on it or its implementation.
https://codeforces.me/gym/105657/problem/C
Parameters
- The polygon is convex
- The point is not strictly inside
What are the tangents to a polygon from a point?
The tangents of a polygon with respect to a point are the lines that pass through the point outside the polygon and touch the polygon at exactly one vertex or along one side, without crossing its interior.
Why are these useful?
- Solve difficult problems
- Solve problems related to visibility or trajectory where the polygon cannot be crossed.
Algorithm
To describe the algorithm, only the left tangent will be specified. At the end, it will be indicated what changes with respect to the right tangent.
The left tangent can be described using the cross product. For a point $$$P_i$$$ and the point $$$p$$$ (for which the tangents are computed), it can be considered the tangent if the cross product with respect to points $$$P_{i+1}$$$ and $$$P_{i-1}$$$ is less than or equal to zero:
Now, we will analyze the behavior of these signs in the following example.
Let us observe that the signs for point C are exactly as we require.
For points G, F, and E, the second condition is satisfied, and for points A, M, T, U, and V, the first condition is satisfied.
However, we can notice that it behaves like a unimodal function.
Thus, it is enough to find the first point for which the first condition is satisfied (in a counterclockwise direction).
To do this, we will do two things.
- Divide the convex hull into its lower and upper layers.
- Divide each layer into two parts to find the left and right tangents.
There will be cases where it is not necessary to use a layer, as in the previous example. Determining whether it is necessary or not would only add more difficulty and does not change the complexity.
The same example illustrated on the division.
When dividing the convex hull, we must take into account that if it is a single point that is farthest to the left (smallest x), it must be in both layers, and the same applies to the point farthest to the right (largest x).
To divide each layer into two parts, one containing the points to the left of the point for which the tangents are calculated, and the other containing the points to the right, a binary search can determine the division.
For the right tangent, we will use these conditions:
Finally, the complexity analysis: a total of six binary searches will be performed, one for each layer and one for each of the four divisions of the polygon, resulting in $$$O(\log n)$$$.
Musical recommendation: Visita, Enjambre ^^
Auto comment: topic has been updated by Jose_17 (previous revision, new revision, compare).
very nice i liked it