P8093-思维、递推
- 如果
a > b :无穷大次操作
证(fei)明(hua):
因为乘法和加法只能使得
a 变大,不能使得a 变小,所以永远不可能达成目标。
- 如果
a * 2 > b :> 证明: > > 如果先将 $a$ 乘一下,那么就转换为第 $1$ 种情况,无解。所以只能加。 - 如果 $b\ \text{mod}\ 2 = 1$: $f(a, b - 1) + 1$ 次操作 > 解释: > > 先将 $a$ 变为 $b - 1$,再加一次。 - 如果 $b\ \text{mod}\ 2 = 0$ 且 $a \leq \dfrac{b}{2} > 解释: > > 先将 $a$ 变为 $\dfrac{b}{2}$,再乘一次。 其实上面的第二个条件“$a \leq \dfrac{b}{2}$”是判断有解的情况
其他详情见代码。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <limits.h>
#include <cstring>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f, INF_BIT = 0x3f;
const int N = 1e5 + 10;
LL t;
LL a, b;
LL f(LL a, LL b){
if(a > b) return 1e18;
if(a * 2 > b) return b - a;
if(b % 2 == 1) return f(a, b - 1) + 1;
if(b % 2 == 0 && a <= b / 2) return f(a, b / 2) + 1;
}
LL solve(LL a, LL b){
LL cnt1 = 0; //光由除操作和加操作的最小操作次数
if(a == b) return 0;
LL ret = 1e18;
//此处改成do...while循环了,直接while循环会被卡
do{
//可以随时设当前为分界点
LL cnt2 = f(a, b);
ret = min(ret, cnt1 + cnt2);
if(a % 2 == 1) a++;
else a /= 2;
cnt1++;
}while(a > 1);
return ret;
}
int main(){
scanf("%lld", &t);
while(t--){
scanf("%lld%lld", &a, &b);
printf("%lld\n", solve(a, b));
}
return 0;
}