寒假每日一题(B

思路:分一下奇偶,然后记忆化搜索(第一次写记忆化,卡了半天。。。)

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
typedef long long ll;
map<ll,ll> f;
ll x,y;
ll solve(ll y)
{
    if(f.count(y))    return f[y];
    ll res = y - x;   //如果y比X大记录一下从X到y需要加多少下。
    if(y <= x)    return x - y;  //如果y比X小返回从X到y需要减多少下(不能除只能减)
    if(y % 2 == 0)    res = min(res,solve(y / 2) + 1); //如果此时y是偶数,看看最少需要多少下能从x变成y
    else    res = min(res,min(solve(y +1) + 1,solve((y -1)) + 1)); //如果此时y是奇数,就要先变成偶数,然后搜一下最少需要多少下能从x变成y
    return f[y] = res;    //记忆化从x到y需要操作多少下
}
int main()
{
    cin >> x >> y;
    cout << solve(y);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/sszywq/p/14279763.html