Crossing Diagonals
Time limit1sMemory limit128 MB
Count crossing pairs among m chosen diagonals of a regular n-gon, ignoring diagonals that only share a vertex.
- Level
Medium6 of 10
- Topics
- Sorting, Prefix sum, Implementation
- Solved
- No attempts yet
Problem
You are given a regular polygon with vertices, and of its diagonals have been selected. Count how many pairs of the selected diagonals cross each other. Two diagonals cross when they intersect strictly inside the polygon; two diagonals that share only a common vertex (endpoint) are not counted as crossing.
Write a program that:
- reads the description of the polygon and the selected diagonals from standard input,
- counts the number of pairs of diagonals that cross,
- writes that number to standard output.
Input
The first line contains two integers and , separated by a single space, where is the number of vertices of the polygon and is the number of selected diagonals (, ).
Each of the next lines describes one diagonal. The -th of these lines contains two integers and (), separated by a single space, denoting the diagonal that joins vertex with vertex . The vertices of the polygon are numbered from to in counter-clockwise order.
You may assume that every pair of numbers describes a valid diagonal (never a single vertex, and never an edge of the polygon), and that all diagonals in the input are distinct.
Output
Print a single integer: the number of pairs of selected diagonals that cross. If no pair of diagonals crosses, print .
Hint

In the picture above, the solid lines and the dashed lines show two different sets of selected diagonals on the same polygon.