A. Add or XOR
Problem Statement
You are given two non-negative integers and . You can apply two types of operations on any number of times and in any order:
- . The cost of this operation is .
- , where denotes the bitwise XOR operation. The cost of this operation is .
Now you are asked to make . If it’s possible, output the minimum cost; otherwise, report it.
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The only line of each test case contains four integers () — the two integers given to you and the respective costs of two types of operations.
Output
For each test case, output an integer — the minimum cost to make , or if it is impossible.
Solution
The second operation (XOR with 1) can increase the value of by 1 when is even and decrease the value of by 1 when is odd.
We can only reach from if , since both operations can only increase (except when is odd and we XOR with 1, which decreases by 1).
The strategy is as follows:
- If and is odd, we can reach by XORing once, which costs .
- If , no operations needed, so return .
- If , we need to increase by units.
- Else we cannot reach from , so return
-1.
For each unit increase, we can either:
- Use operation 1 (add 1) with cost
- Use operation 2 (XOR with 1) when is even, which costs .
Since the data is small, we can directly increase one by one until it reaches and calculate the cost accordingly.
But actually, the cost can be calculated directly:
- If , always use operation 1 (add 1) to reach from , which costs .
- Otherwise, the cost , and if is odd, we need one more operation of type 1 or type 2.