Editorial for Baltic OI '11 P7 - Polygon
Submitting an official solution before solving the problem yourself is a bannable offence.
Let's first find the total length of grid line segments which lie strictly inside the given polygon and are horizontal. Assume that we cut the given polygon by horizontal grid lines. Therefore, the polygon will be cut into trapezoids and triangles with height . Bases of trapezoids and triangles are horizontal segments (we may think that a triangle is a trapezoid with one base length equal to ). Now the area of a polygon can be expressed as the sum of trapezoid areas:
On the other hand, the area of the polygon can be calculated using only given vertex coordinates and in the given order as:
In this formula and .
Every horizontal gridline segment appears in the sum at most twice (zero times if it is outside polygon, once if it is on the polygon's side and twice if it is strictly inside). These segments which appear two times in sum has total weight . Segments that appear only once have total weight .
To calculate the total sum of segments that lie strictly inside the polygon, we need to subtract from the polygon area (calculated using formula ) the total length of horizontal polygon perimeter segments divided by .
Total length of vertical gridline segments can be calculated in exactly the same way.
It is easy to see that the correct answer multiplied by always is an integer so there is no need to do calculations in the floating point numbers.
Algorithm complexity is .
For the given constraints all calculations can be done using bit integers.
Comments