Codeforces 520B Two Buttons 题解

来源:互联网 发布:儿童编程培训班加盟 编辑:程序博客网 时间:2024/05/28 05:15

题意

给你一个数n,每次操作你可以把它乘2或者是减1,问至少需要多少次操作可以把n变为m

思路

剪枝bfs,如果操作后的数大于104这个上界,或者小于1这个下界就可以减掉,如果这个数之前出现过就可以减掉

代码

#include <cstdio>#include <queue>using namespace std;queue<pair<int,int> > q;bool used[10001];int main(){    int n,m,ans=0;    pair<int,int> t;    scanf("%d%d",&n,&m);    q.push(make_pair(n,0));    while(!q.empty())    {        used[q.front().first]=true;        if(q.front().first==m)        {            ans=q.front().second;            break;        }        if(q.front().first*2>=1&&q.front().first*2<=10000&&!used[q.front().first*2])            q.push(make_pair(q.front().first*2,q.front().second+1));        if(q.front().first-1>=1&&q.front().first-1<=10000&&!used[q.front().first-1])            q.push(make_pair(q.front().first-1,q.front().second+1));        q.pop();    }    printf("%d\n",ans);    return 0;}