题目描述
Now given two integers x and y, you can reverse every consecutive three bits in arbitrary number’s binary form (any leading zero can be taken into account) using one coin. Reversing (1,2,3) means changing it into (3,2,1).
Could you please find a way that minimize number of coins so that x = y? If you can, just output the minimum coins you need to use.
输入
The first line of input file contains only one integer T (1≤T≤10000) indicating number of test cases.
Then there are T lines followed, with each line representing one test case.
For each case, there are two integers x, y (0≤x,y≤1018) described above.
输出
Please output T lines exactly.
For each line, output Case d: (d represents the order of the test case) first. Then output the answer in the same line. If there is no way for that, print -1 instead.
样例输入
复制样例数据
3 0 3 3 6 6 9
样例输出
Case 1: -1 Case 2: 1 Case 3: 2
提示
Sample 1: Considering following two binary string:
0: 0 ...0000
3: 0 ...0011
There is no way to achieve the goal.
Sample 2: Considering following two binary string:
3: 0 ...0011
6: 0 ...0110
You can reverse the lowest three digits in 3 so that 3 is changed into 6.
You just need to perform one reverse so that the minimum coin you need to use is 1.
解题思路:
在翻转的时候中间一个数是不变的例如(011,操作后变为110),只有a二进制偶数位上的1和奇数位上的1与b上的偶数和奇数位上的数量都相等才能变换。发现了这点只需要把a,b都转成二进制数,从a的第一位开始如果与b的不相同则从a后找第一个和b的该位相同的数,需要操作的次数就是这两位之间的距离除二。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
typedef long long ll;
using namespace std;
const int maxn = 100;
int l1,l2;
int A[100],B[100];
int main()
{
int t;
cin>>t;
int x = 0;
while(t--){
x++;
l1 = 100;
l2 = 100;
ll a,b;
cin>>a>>b;
memset(A,0,sizeof(A));
memset(B,0,sizeof(B));
while(a){
A[l1--] = (a&1);
a/=2;
}
while(b){
B[l2--] = (b&1);
b/=2;
}
int res = 0;
int flag,i;
int flag2 = 0;
for(i = 1;i <= 100;i++){
flag = 0;
if(A[i] != B[i]){
for(int j = i;j<=100;j += 2){
if(A[j] == B[i]){
res += (j-i)/2;
A[j] = A[i];
A[i] = B[i];
flag = 1;
break;
}
}
}
if(A[i] != B[i]){
flag2 = 1;
break;
}
}
if(flag2 == 0)
printf("Case %d: %d\n",x,res);
else
printf("Case %d: -1\n",x,res);
}
}