There are people in the queue. The people are numbered : each person holds a number . Starting from the second person served, if the person served immediately before him/her holds number , and the person holds , it will generate a cost of where denotes the bitwise exclusive OR of and . The total cost will be the sum of the costs resulting from serving all people in the queue. Formally, assume in the actual order of people served, the numbers they have are , the resulting cost will be
Now you want to reorder the queue so that the total cost is minimized. In other words, you don't have to serve people in exact order of the queue. The caveat is for each person , it has a tolerance level : if a person has position in the original queue, and , then person will become angry if is served before . You cannot let this happen. Under this constraint, what the minimum cost will be?
To compute , write and in binary, and for each bit, we compute the corresponding bit in using the rule that and . In other words, the -th bit of in binary is 1 if and only if the -th bit of and are different. In C/C++, this is represented by operator ^
. For example, to compute , you can do the following:
- Write and in binary: .
- For each bit, check if they differ: starting from the least significant (rightmost) bit, we see and are the same, and are different, while and are same again.
- As a result, .
Input Specification
The first line consists of an integer denoting the number of test cases.
For each test case, the first line consists of a positive integer denoting the number of students in the queue.
Next, there are lines, each line has two non-negative integers separated by a single space denoting the number person holds and the tolerance level of person .
Output Specification
For each test case, output a line with an integer denoting the minimum cost.
Sample Input
2
5
5 2
4 1
12 0
3 3
2 2
2
7 0
5 0
Sample Output
16
2
Explanation
In the first case, the optimal ordering is . The total cost is thus
In the second case, the only possible order is , which generates a cost of .
Constraints
For all test cases, , , , and .
Scoring
There are 25 test cases for this problem.
This table summarizes the bounds of the test cases:
Test case | |||
---|---|---|---|
1 | 6 | 2 | 1000 |
2 | 8 | 3 | 16 |
3 | 10 | 1 | 32 |
4 | 12 | 4 | 128 |
5 | 16 | 7 | 1000 |
6 | 18 | 1 | |
7 | 20 | 1 | 128 |
8 | 5 | 32 | |
9 | 400 | 1 | 128 |
10 | 500 | 6 | 1000 |
11 | 7 | ||
12 | 600 | 2 | 16 |
13 | 3 | 200 | |
14 | 700 | 1 | 64 |
15 | 4 | 512 | |
16 | 7 | 1000 | |
17 | 800 | 1 | 128 |
18 | 2 | 32 | |
19 | 900 | 1 | 200 |
20 | 6 | 512 | |
21 | 1000 | 1 | 1000 |
22 | 5 | 32 | |
23 | 6 | 600 | |
24 | 7 | 128 | |
25 | 7 | 1000 |
Comments