This page is still under construction.

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

City Horizon

Interview

Time limit1sMemory limit128 MB

Summary
Given N axis-aligned rectangles that all rest on the ground, compute the area of their union.
Level

Medium7 of 10

Topics
Segment tree, Divide and conquer, Sorting, Geometry
Solved
No attempts yet

Problem

Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the city horizon and admire the beautiful silhouettes formed by the rectangular buildings.

The entire horizon is represented by a number line, and NN buildings stand along it (1≤N≤40,0001 \le N \le 40{,}000). Building ii's silhouette has a base that spans the horizon from position AiA_i to BiB_i (1≤Ai<Bi≤1,000,000,0001 \le A_i < B_i \le 1{,}000{,}000{,}000) and has height HiH_i (1≤Hi≤1,000,000,0001 \le H_i \le 1{,}000{,}000{,}000). Every building rests on the ground (y=0y = 0).

Determine the area, in square units, of the combined silhouette formed by all NN buildings — that is, the area covered by the union of all the rectangles. Overlapping regions must be counted only once.

Input

  • Line 1: A single integer NN
  • Lines 2 to N+1N+1: Line i+1i+1 describes building ii with three space-separated integers AiA_i, BiB_i, and HiH_i.

Output

  • Line 1: The total area, in square units, of the silhouette formed by all NN buildings.

Hint

In the example above, the first building overlaps with the fourth building over an area of 11 square unit. Counting the overlap only once, the total area is 3×1+1×4+2×2+2×3−1=163 \times 1 + 1 \times 4 + 2 \times 2 + 2 \times 3 - 1 = 16.

Examples1

  1. Example 1

    Input
    4
    2 5 1
    9 10 4
    6 8 2
    4 6 3
    
    Expected output
    16