Horizontally Visible Segments

Time limit1sMemory limit128 MB

Summary
Given disjoint vertical segments, count triangles formed by triples that are pairwise horizontally visible using a sweep and visibility structure.
Level

Hard8 of 10

Topics
Sorting, Geometry, Segment tree
Solved
No attempts yet

Problem

You are given a set of pairwise disjoint vertical line segments in the plane (no two segments share any point).

Two segments are said to be horizontally visible if they can be joined by a horizontal segment that has no common point with any other vertical segment. Three distinct vertical segments form a triangle of segments if each of the three pairs among them is horizontally visible.

For each data set, read the description of a set of vertical segments and report how many triangles of segments it contains.

Input

The first line contains one positive integer dd, the number of data sets, with 1≤d≤201 \le d \le 20. The data sets follow.

The first line of each data set contains one integer nn with 1≤n≤80001 \le n \le 8000, the number of vertical segments. Each of the next nn lines contains three non-negative integers yi′y_i', yi′′y_i'', xix_i separated by single spaces: the yy-coordinate of the lower endpoint, the yy-coordinate of the upper endpoint, and the xx-coordinate of the ii-th segment. The coordinates satisfy 0≤yi′<yi′′≤80000 \le y_i' < y_i'' \le 8000 and 0≤xi≤80000 \le x_i \le 8000, and the segments are pairwise disjoint.

Output

Print exactly dd lines, one per data set. The ii-th line must contain a single integer: the number of triangles of segments in the ii-th data set.

Examples9

  1. Example 1

    Input
    1
    5
    0 4 4
    0 3 1
    3 4 2
    0 2 2
    0 2 3
    
    Expected output
    1
    
  2. Example 2

    Input
    1
    1
    0 5 0
    
    Expected output
    0
    
  3. Example 3

    Input
    1
    3
    0 10 0
    0 3 1
    0 10 2
    
    Expected output
    1
    
  4. Example 4

    Input
    1
    3
    0 10 0
    0 10 1
    0 10 2
    
    Expected output
    0
    
  5. Example 5

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

    Input
    1
    3
    0 3 1
    3 6 2
    0 6 3
    
    Expected output
    1
    
  7. Example 7

    Input
    1
    4
    0 20 0
    0 1 1
    3 4 1
    6 7 1
    
    Expected output
    0
    
  8. Example 8

    Input
    1
    5
    0 1 0
    0 1 1
    0 1 2
    0 1 3
    0 1 4
    
    Expected output
    0
    
  9. Example 9

    Input
    1
    2
    0 2 5
    5 7 5
    
    Expected output
    0