【codeforces 520B】Two Buttons

【题目链接】:http://codeforces.com/contest/520/problem/B

【题意】

给你一个数n;
对它进行乘2操作,或者是-1操作;
然后问你到达m需要的步骤数;

【题解】

操作的过程中;
可能会大于m吧;
也不知道是多少倍;
但也没事,不差那一点时间.
bfs

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define ps push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%lld",&x)
#define ref(x) scanf("%lf",&x)

typedef pair<int, int> pii;
typedef pair<LL, LL> pll;

const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
const double pi = acos(-1.0);
const int N = 1e5+100;

int mi[N];

int n, m;
queue <int> dl;

int main()
{
    //freopen("F:\rush.txt", "r", stdin);
    rei(n), rei(m);
    if (n == m) return puts("0"), 0;
    dl.push(n); mi[n] = 0;
    while (!dl.empty())
    {
        int x = dl.front();
        dl.pop();
        int y = x * 2;
        if (y <= 100000)
        {
            if (!mi[y])
            {
                mi[y] = mi[x] + 1;
                dl.push(y);
            }
        }
        y = x - 1;
        if (y > 0)
        {
            if (!mi[y])
            {
                mi[y] = mi[x] + 1;
                dl.push(y);
            }
        }
    }
    printf("%d
", mi[m]);
    //printf("
%.2lf sec 
", (double)clock() / CLOCKS_PER_SEC);
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626484.html