Counting Bow Ties
Time limit2sMemory limit256 MB
Count 4-cycles in a bipartite graph defined by M rectangles over vertex ranges, with N up to 1e9.
- Level
Hard8 of 10
- Topics
- Geometry, Combinatorics, Sorting, Prefix sum
- Solved
- No attempts yet
Problem
A bipartite graph has vertices. of them hang from the ceiling and the other sit on the floor. The ceiling vertices are numbered 1 through , and the floor vertices are numbered the same way.
trapezoids connect the ceiling to the floor. Each trapezoid is given by the segment it occupies on the ceiling and the segment it occupies on the floor. Ceiling vertex and floor vertex are joined by an edge when at least one trapezoid satisfies both and . When several trapezoids cover the same edge, the edge still counts once.
A simple cycle of length 4 in this graph is called a bow tie. Two different ceiling vertices , and two different floor vertices , form one bow tie when all four edges , , , are present. Two bow ties are different when their edge sets differ in at least one element.
Given the shape of the graph, count the bow ties.

A graph with 9 vertices on each side and two trapezoids. The dashed lines mark one bow tie in it.
Input
The first line contains () and (), separated by a space. The graph has vertices and there are trapezoids.
Each of the next lines contains one trapezoid in the form (, ).
Output
Print the number of bow ties modulo .