A. Add or XOR

Problem Statement

You are given two non-negative integers aa and bb. You can apply two types of operations on aa any number of times and in any order:

  1. aa+1a \leftarrow a + 1. The cost of this operation is xx.
  2. aa1a \leftarrow a \oplus 1, where \oplus denotes the bitwise XOR operation. The cost of this operation is yy.

Now you are asked to make a=ba = b. 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 tt (1t1041 \leq t \leq 10^4). The description of the test cases follows.

The only line of each test case contains four integers a,b,x,ya, b, x, y (1a,b100,1x,y1071 \leq a, b \leq 100, 1 \leq x, y \leq 10^7) — 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 a=ba = b, or 1-1 if it is impossible.

Solution

The second operation (XOR with 1) can increase the value of aa by 1 when aa is even and decrease the value of aa by 1 when aa is odd.

We can only reach bb from aa if aba \leq b, since both operations can only increase aa (except when aa is odd and we XOR with 1, which decreases aa by 1).

The strategy is as follows:

  • If a=b+1a = b + 1 and aa is odd, we can reach bb by XORing once, which costs yy.
  • If a=ba = b, no operations needed, so return 00.
  • If a<ba < b, we need to increase aa by (ba)(b - a) units.
  • Else we cannot reach bb from aa, so return -1.

For each unit increase, we can either:

  1. Use operation 1 (add 1) with cost xx
  2. Use operation 2 (XOR with 1) when aa is even, which costs yy.

Since the data is small, we can directly increase aa one by one until it reaches bb and calculate the cost accordingly.

But actually, the cost can be calculated directly:

  • If xyx \leq y, always use operation 1 (add 1) to reach bb from aa, which costs (ba)x(b - a) \cdot x.
  • Otherwise, the cost =(ba)÷2(x+y)= (b - a) \div 2 \cdot (x + y), and if (ba)(b - a) is odd, we need one more operation of type 1 or type 2.

submission link