This page is still under construction.

Parts of this page are still being built. What you see may change.

Area and Perimeter of a Union of Rectangles

Time limit1sMemory limit128 MB

Summary
Given up to 10000 axis-parallel rectangles on an integer grid, compute the area of their union (and its perimeter when r=2), counting overlaps once.
Level

Hard8 of 10

Topics
Segment tree, Sorting, Prefix sum, Geometry
Solved
No attempts yet

Problem

Several rectangular sheets are placed on a plane. Write a program that computes the area, or the perimeter, of the region covered by these sheets.

Regarding the plane as a coordinate plane, the sheets are arranged so that the following two conditions hold.

  1. The xx and yy coordinates of the four vertices of every sheet (rectangle) are integers between 00 and 1000010000 inclusive, and each side of every rectangle is parallel to the xx-axis or the yy-axis.
  2. The number of sheets is at most 1000010000.

Sheets may overlap one another; overlapping area is counted only once. The perimeter is the total length of the boundary of the covered region, including the boundary of any hole that appears inside it.

Input

The first line contains the number of rectangles nn and an integer rr indicating the query type, separated by a space. Each of the next nn lines contains the lower-left vertex (x1,y1)(x_1, y_1) and the upper-right vertex (x2,y2)(x_2, y_2) of a sheet, given in the order x1x_1, y1y_1, x2x_2, y2y_2 and separated by spaces.

Output

If r=1r = 1, print the area of the covered region on the first line. If r=2r = 2, print the area on the first line and the perimeter on the second line. In either case, end the output with a newline.

Examples4

  1. Example 1

    Input
    5 1
    0 0 3 2
    1 1 2 5
    0 4 6 5
    3 3 5 6
    5 0 7 6
    
    Expected output
    29
    
  2. Example 2

    Input
    5 2
    0 0 3 2
    1 1 2 5
    0 4 6 5
    3 3 5 6
    5 0 7 6
    
    Expected output
    29
    38
    
  3. Example 3

    Input
    2 2
    0 0 8 9
    0 0 9 8
    
    Expected output
    80
    36
    
  4. Example 4

    Input
    3 2
    2 2 8 8
    3 0 4 9
    5 0 7 9
    
    Expected output
    45
    36