Count 4-cycles in a bipartite graph defined by M rectangles over vertex ranges, with N up to 1e9.
Hard8GeometryCombinatoricsSortingPrefix sumNo attempts yetTime limit2sMemory limit256 MBA bipartite graph has 2N vertices. N of them hang from the ceiling and the other N sit on the floor. The ceiling vertices are numbered 1 through N, and the floor vertices are numbered the same way.
M trapezoids connect the ceiling to the floor. Each trapezoid is given by the segment [sx,ex] it occupies on the ceiling and the segment [sy,ey] it occupies on the floor. Ceiling vertex i and floor vertex j are joined by an edge when at least one trapezoid satisfies both sx≤i≤ex and sy≤j≤ey. 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 i1, i2 and two different floor vertices j1, j2 form one bow tie when all four edges (i1,j1), (i1,j2), (i2,j1), (i2,j2) 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.
The first line contains N (1≤N≤109) and M (0≤M≤1000), separated by a space. The graph has 2N vertices and there are M trapezoids.
Each of the next M lines contains one trapezoid in the form sx ex sy ey (1≤sx≤ex≤N, 1≤sy≤ey≤N).
Print the number of bow ties modulo 109+7.