Grabbing Land

Time limit1sMemory limit128 MB

Summary
Split N rectangles into groups, each group costing the product of its max width and max height, minimizing the total cost.
Level

Hard8 of 10

Topics
Sorting, Dynamic programming, Greedy
Solved
No attempts yet

Problem

Farmer Sangheon wants to buy all NN plots of land from Seonjae's real estate. Each plot is a rectangle with width WiW_i and height HiH_i.

Normally a single plot costs Wi×HiW_i \times H_i, but business has been slow, so Seonjae now offers the following bundle discount:

  • When several plots are bought together as one bundle, the price of that bundle is (the maximum WiW_i among the plots in the bundle) ×\times (the maximum HiH_i among the plots in the bundle).

Sangheon will split the NN plots into one or more bundles and buy them all; every plot must belong to exactly one bundle. Because the total price depends on how the plots are grouped, find the minimum total cost to buy all of the plots.

Input

The first line contains the number of plots NN. (1≤N≤500001 \le N \le 50000)

Each of the next NN lines contains the width WiW_i and height HiH_i of a plot, separated by a space. (1≤Wi,Hi≤10000001 \le W_i, H_i \le 1000000)

Output

Print the minimum total cost to buy all of the plots on a single line.

Hint

For example, with the four plots (100,1)(100, 1), (15,15)(15, 15), (20,5)(20, 5), and (1,100)(1, 100), you can split them into the three bundles {(100,1)}\{(100,1)\}, {(1,100)}\{(1,100)\}, and {(15,15),(20,5)}\{(15,15),(20,5)\}. The cost is then 100×1+1×100+20×15=500100 \times 1 + 1 \times 100 + 20 \times 15 = 500.

Examples5

  1. Example 1

    Input
    4
    100 1
    15 15
    20 5
    1 100
    
    Expected output
    500
    
  2. Example 2

    Input
    1
    5 7
    
    Expected output
    35
    
  3. Example 3

    Input
    2
    3 3
    5 5
    
    Expected output
    25
    
  4. Example 4

    Input
    2
    1000000 1
    1 1000000
    
    Expected output
    2000000
    
  5. Example 5

    Input
    1
    1000000 1000000
    
    Expected output
    1000000000000