#P2157. Minimizing Cooking Time with Limited Overtaking

    ID: 15438 Type: Default 1000ms 256MiB

Minimizing Cooking Time with Limited Overtaking

Minimizing Cooking Time with Limited Overtaking

The school cafeteria has a unique way of serving meals. There are n students in a queue. Each student i is characterized by an integer flavor preference fi and a tolerance Bi (a non‐negative integer). The cooking works as follows: the chef prepares one dish at a time. The time to cook a dish immediately after a dish with flavor a (for the previous student) when the current dish has flavor b is given by

\mbox{time} = (a\,|\,b)-(a\,&\,b)

where | and & denote the bitwise OR and AND operations respectively. Note that the first dish incur no cooking time. It can be verified that

(a\,|\,b)-(a\,&\,b)=\mbox{popcount}(a\oplus b),

i.e. the cooking time equals the number of bits which are different between a and b.

Normally the dishes would be served strictly following the initial queue order (students numbered 1 through n). However, to reduce the total cooking time the cafeteria is sometimes allowed to change the serving order. There is a catch though: each student i is only willing to tolerate at most the immediately following Bi students overtaking him. More formally, if in the final serving order a student originally at position i is overtaken by any student originally behind him, then every such student j must satisfy jiBi.j-i\le B_i.

If any student finds that someone not among his immediately next Bi in the original order is served before him, he becomes extremely angry.

Your task is to determine the minimum total cooking time needed to cook dishes for all students, under a serving order that respects everyone’s tolerance.

inputFormat

The first line contains an integer n (the number of students).

Then follow n lines. The i-th of these lines contains two non‐negative integers fi and Bi, where fi represents the flavor preference and Bi represents the tolerance of the student originally at position i.

Note: The first dish prepared has no cooking time.

outputFormat

Output a single integer: the minimum total cooking time needed to serve all students while respecting the tolerance constraint.

sample

3
1 1
2 0
3 1
3