This page is still under construction.

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

Where to Build a Brewery?

Time limit3sMemory limit512 MB

Summary
On a ring of cities with given edge lengths and demands, pick the city minimizing total demand-weighted shortest-path distance around the ring.
Level

Medium7 of 10

Topics
Prefix sum, Two pointers, Greedy, Math
Solved
No attempts yet

Problem

The residents of the island of Abstinence love alcohol-free beer. Until now it was imported from Poland, but this year one of the island's cities will build a brewery. Every city sits on the coast, and they are all linked by a single highway that runs around the island along the shore, so the cities form one big ring. The investor has gathered, for every city, the number of beer tanks it needs each day (its demand) and the distances between neighbouring cities. Moving one tank of beer one mile costs 1 thaler. The daily transport cost is the total cost of shipping the required number of tanks from the brewery to every city, where the beer for each city travels along the shorter of the two directions around the ring. This cost depends on where the brewery is built, and the investor wants to choose the city that makes it as small as possible.

Write a program that

  • reads the number of cities, the distances between them, and each city's daily beer demand,
  • computes the minimal daily transport cost,
  • writes the result to standard output.

Input

The first line contains one integer nn, the number of cities (5≤n≤10 0005 \le n \le 10\,000). Cities are numbered along the highway, so neighbouring cities have consecutive numbers, and cities 11 and nn are neighbours too. Each of the next nn lines contains two non-negative integers separated by a single space: ziz_i and did_i. Here ziz_i is the daily beer demand of city ii, and did_i is the distance in miles from city ii to the next city along the highway. The total length of the highway does not exceed 1 000 0001\,000\,000 miles. The demand of each city does not exceed 1 0001\,000 tanks.

Output

Print a single integer: the minimal daily transport cost.

Examples2

  1. Example 1

    Input
    6
    1 2
    2 3
    1 2
    5 2
    1 10
    2 3
    
    Expected output
    41
    
  2. Example 2

    Input
    5
    1 1
    1 1
    1 1
    1 1
    1 1
    
    Expected output
    6