problems / 262

Suki's Overlapping Park Visits

medium intervals sorting binary-search 1000 ms · 256 MB

Suki's Overlapping Park Visits

Suki, the curly black dog with the grey beard and white paws, loves the park because it is full of friends. Today she sniffed her way through the park's visitor log, which lists n dog visits. Visit i began at minute l_i and ended at minute r_i, and the dog was in the park during every moment from l_i to r_i, both ends included. One of the visits is Suki's own.

Two visits met if both dogs were in the park at some common moment. A visit that ends at the exact minute another one begins counts as meeting it too: the two dogs had a quick sniff at the gate.

Suki wants to know how many pairs of visits met. Count the unordered pairs of different visits {i, j} for which some moment t satisfies l_i ≤ t ≤ r_i and l_j ≤ t ≤ r_j.

Input

The first line contains an integer n (1 ≤ n ≤ 2·10^5), the number of visits.

Each of the next n lines contains two integers l_i and r_i (0 ≤ l_i ≤ r_i ≤ 10^9), the start and end minute of visit i. Different visits may be identical.

Output

Print one integer: the number of pairs of visits that met. It can exceed 2^31, so use a 64-bit integer.

Notes

In the first example, the pairs that met are visits 1 and 2 (minutes 3 to 5), visits 2 and 3 (they touch at minute 7) and visits 3 and 4 (minutes 9 to 10). Visit 1 meets neither visit 3 nor visit 4, and visit 2 does not meet visit 4.

In the second example, every visit is a single minute: the two visits at minute 5 met, and so did each pair of the three visits at minute 8, for 1 + 3 = 4 pairs.

Example 1

Input

4
1 5
3 7
7 10
9 12

Output

3

Example 2

Input

6
8 8
5 5
1 1
8 8
5 5
8 8

Output

4

Hints · reveal one at a time if you're stuck

Hint 1

Counting the pairs that met directly is awkward. What does it look like when two visits did not meet?

Hint 2

Two visits miss each other exactly when one of them ends strictly before the other starts, and only one of the two can be that earlier visit. So every pair that did not meet can be counted exactly once, from the visit that starts later.

Hint 3

For one visit you need how many end minutes are strictly less than its start. Sort all the end minutes once, and each such count is a binary search. Mind the strictness: touching visits met.

report an issue Prefer your own editor? sooks prep 262 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.