Under construction

Still being built. Things may change

Rhythm Game of Balls

Time limit1sMemory limit1024 MB

Summary
Given N balls on a line that are stationary or moving left or right, find the total points scored from collisions until none occur.
Level

Medium6 of 10

Topics
Greedy, Sorting, Stack
Solved
No attempts yet

Problem

A line of infinite length has NN balls on it. Each ball is either stationary, moves to the left, or moves to the right. At the start, all ball positions are different.

Hyeonje makes rhythm games and noticed a steady beat in the way moving balls hit each other. The game starts at 0 points. Each time balls collide, points are scored and the ball states change as follows.

  • When a ball moving left and a ball moving right collide, both reverse their directions. This scores 1 point.

  • When a moving ball hits a stationary ball, the moving ball stops at that spot, and the stationary ball starts moving in the direction the moving ball was going. This scores 2 points.

  • When a ball moving left, a stationary ball, and a ball moving right collide at the same time, the left-moving and right-moving balls both reverse direction, and the stationary ball stays where it is. This scores 5 points.

If one collision meets several conditions, only the condition with the highest score applies.

Find the total score after enough time has passed that no more collisions occur. The total score is the sum of all points earned.

Every moving ball keeps a speed of 1, and a ball that starts moving after a collision also has speed 1. Balls are assumed to be small enough that their length and volume are negligible. Apart from collisions, each ball keeps its direction and speed.

Input

The first line contains the number of balls NN. (1≤N≤500 000)(1\le N\le 500\,000)

Each of the next NN lines contains an integer aia_i and an integer did_i, separated by a space. (∣ai∣≤1018(|a_i|\le 10^{18}, ∣di∣≤1)|d_i|\le 1)

aia_i is the coordinate of the ball on the line. did_i gives the initial state as follows.

  • di=0d_i=0: the ball is stationary.
  • di=−1d_i=-1: the ball moves to the left.
  • di=1d_i=1: the ball moves to the right.

All ball positions are different.

Output

Print the total score after enough time has passed that no more collisions occur.

Examples4

  1. Example 1

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

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

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

    Input
    4
    4 1
    5 0
    6 0
    8 -1
    
    Expected output
    9