题目链接
题目描述
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组输入,每组输入包含两个数字x和y(long long int)。对x有一种操作,可以将 x的二进制 任意相邻的三个位逆置。
问最少进行多少次操作,可以使得x等于y
【解题思路】
将这些数字都变成二进制在放入到一个数组中去,由于三位一交换相当于中间的不变,两边的换个位置,所以如果奇数位或者偶数位的1或者0的数量不一样的话,那么直接输出-1;否则就需要比较了,这时拿一个数组来记录下对应的1的位置,然后这些1其实就是我们要进行交换的,但是因为隔着两个位置才换一次,所以要除上2才行
#include<stdio.h>
#include<iostream>
using namespace std;
#define LL long long int //将long long int重新定义成LL,方便书写
LL t, x, y, count_num1 = 0, count_num2 = 0, ans=0, count_a = 0,count_b=0,count_max=0;
LL a[1000], b[1000],a1[100],b1[1000];
int case_num = 1;
int main() {
cin >> t;
for (LL i = 0; i < t; i++) {
ans = count_num1 = count_num2 = 0;
for (LL j = 0; j < count_max; j++) {
a[j] = b[j] = a1[j] = b1[j] = 0;
}
cin >> x >> y;
cout << "Case " << case_num++ << ": ";
while (x) {
a[count_num1] = x & 1;
x = x >> 1, count_num1++;//count_num1用来记录x的数据的长度或者说位数
}
while (y) {
b[count_num2] = y & 1;
y = y >> 1, count_num2++;//count_num2用来记录y的数据的长度或者说位数
}
count_max = max(count_num1, count_num2);//这里需要记录下两个数转成二进制之后最长的数的位数有多少位
count_a = count_b = 0;
for (LL j = 0; j < count_max; j += 2) {
if (a[j] == 1) a1[count_a++] = j;
if (b[j] == 1) b1[count_b++] = j;
}
if (count_a != count_b) {
cout << "-1" << endl;
continue;
}
for (LL j = 0; j < count_a; j++) {
ans += abs(a1[j] - b1[j])>>1;
}
count_a = count_b = 0;
for (LL j = 1; j < count_max; j += 2) {//一定要全部遍历完啊!!!
if (a[j] == 1) a1[count_a++] = j;
if (b[j] == 1) b1[count_b++] = j;
}
if (count_a != count_b) {
cout << "-1" << endl;
continue;
}
for (LL j = 0; j < count_a; j++) {
ans += abs(a1[j] - b1[j]) >> 1;
}
cout << ans << endl;
}
return 0;
}
PS:本题在解决的时候一定要注意一些变量要及时地重新赋成0,否则会导致结果出现严重错误!!!