题目描述
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.
题意:
输入t组数据,每组数据包括两个数a,b。定义一次操作为将连续的三个数例如(x,y,z)置换成(z,y,x)。问将数a的二进制需要进行几次操作才能转化为数b。样例6的二进制为0110,9的二进制为1001,那么(0,1,1,0)——>(1,1,0,0)——>(1,0,0,1)
只需要两步操作就行。
思路:
找到数a,b二进制中,奇数位的1的个数ao,bo,偶数位的1的个数ae,be,如果对应的1的个数不同,说明不能转化。
在用变量记录数a,b二进制中,奇数位的1的坐标总和numao,numbo,偶数位的1的坐标总和numae,numbe。
要求的步数实际上就是(abs(ae-be)+abs(ao-bo))/2。
#include<iostream>
#include<cmath>
#include<bitset>
using namespace std;
int main()
{
int n;
cin>>n;
for(int j=1;j<=n;j++)
{
int a,b;
cin>>a>>b;
bitset<64> a1(a);//将数a转化成二进制并且将每一位保存在数组a1中
bitset<64> b1(b);//将数b转化成二进制并且将每一位保存在数组b1中
int ao=0,bo=0,ae=0,be=0,numao=0,numbo=0,numae=0,numbe=0;
for(int i=0;i<64;i++)//ao,bo记录数a,b二进制中奇数位为1的位置坐标总和
{//ae,be记录数a,b二进制中偶数位为1的位置坐标总和
if(i%2==0)//numao,numbo记录奇数的位置1的个数,numae,numbe记录偶数的位置1的个数
{
if(a1[i]==b1[i])
continue;
else
{
if(a1[i]==1){
ao+=i;
numao++;
}
else{
bo+=i;
numbo++;
}
}
}
else
{
if(a1[i]==b1[i])
continue;
else
{
if(a1[i]==1){
ae+=i;
numae++;
}
else{
be+=i;
numbe++;
}
}
}
}
cout<<"Case "<<j<<": ";
if(numao!=numbo||numae!=numbe)
cout<<"-1";
else
{
cout<<(abs(ae-be)+abs(ao-bo))/2;
}
if(j!=n)
cout<<endl;
}
return 0;
}