CF - Cut Length

Author: Benjamin Qi


Official Editorial (Russian)

My Submission

My Code (without template):

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using db = double;
using str = string; // yay python!
using pi = pair<int, int>;
using pl = pair<ll, ll>;

Time Complexity: O(nm)\mathcal{O}(nm)

We'll process each of the mm lines in O(n)\mathcal{O}(n) time each. For a fixed line, let aa and bb be two points on the line. Suppose for simplicity that the line is parallel to the xx-axis.

First, if no vertex of the polygon lies on the line then we can compute all the intersection points of the sides with the line and add / subtract their xx-coordinates appropriately to get the answer. In my solution, dot(b-a,p)/abs(b-a) essentially computes the xx-coordinate of some point pp.

To deal with vertices of the polygon that lie on the line, we can envision shifting the line up or down by some small amount so that no vertex lies on the line. This incorrectly leaves out some sides of the polygon that are collinear with the original line, so we should add the lengths of these sides to the answer. These sides are dealt with by the second if statement within the loop.

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!