C. Strange Test
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich.
Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers aa and bb (a<ba<b). After that, the student can apply any of the following operations any number of times:
- a:=a+1 (increase a by 1),
- b:=b+1 (increase b by 1),
- a:=a | b (replace a with the bitwise OR of a and b).
To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make aa and bb equal.
Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make aa equal to bb.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤1e4 1≤t≤1e4). Description of the test cases follows.
The only line for each test case contains two integers a and b( 1≤a<b≤1e6).
It is guaranteed that the sum of bb over all test cases does not exceed 1e6
Output
For each test case print one integer — the minimum required number of operations to make aa and bb equal.
翻译:
多组输入
第一行为t,表示测试样例数;
接下来每组输入两个正整数数 a,b . b>a;
三种操作 1:a++;
2:b++
3 :a=a|b;
问最少经过多少次操作后a==b;
思路: 数位dp,二进制运算;
容易得出我们最多进行1次3操作,因为a|b>min(a,b)=a(b>a);
如果做了三操作目标还没达到,相当于浪费了一次操作,是不可取的;
我们设经过 若干次操作后a->a1,b->b1;
那么有a1>=a&&a1<b,b1>b;
初始化ans=b-a,更新ans=min(ans,a1+(a1|b1)+1-a-b);
关键是如何找到这样一个b1;
问题变成找到b1>b,a1|b1=b1,使得b1最小;
画一个图就说明问题了
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1010;
ll tt;
int main(){
cin>>tt;
while(tt--){
int a,b;
cin>>a>>b;
int ans=b-a;
for(int a1=a;a1<b;a1++){
int b1=0;
for(int i=21;i>=0;i--)
{
if((b>>i)&1)
{
b1^=(1<<i);
}else {
if((a1>>i)&1)
{
b1^=(1<<i);
break;
}
}
}
ans=min(ans,a1+(a1|b1)+1-a-b);
}
cout<<ans<<endl;
}
return 0;
}