Codeforces Round #295 (Div. 2)---B. Two Buttons( bfs步数搜索记忆 )

B. Two Buttons
time limit per test : 2 seconds
memory limit per test :256 megabytes
input :standard input
output : standard output

Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.

Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?

Input

The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .

Output

Print a single number — the minimum number of times one needs to push the button required to get the number m out of number n.

Sample test(s)
Input
4 6
Output
2
Input
10 1
Output
9
Note

In the first example you need to push the blue button once, and then push the red button once.

In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.

题目和算法分析:

在每组测试数据里,输入n和m的值,求从n变到m最少所需要的变换次数。每次对于n的操作可以是:*2 或者 -1。

比如第一组测试数据:要从n=4变到m=6,需要将n=4-1=3, 再3*2=6=m,这样最小且只需要2步。

通过bfs进行广度优先搜索,注意已经搜索过的数值不进行第二搜索,所以需要标记数组。此外还需要一个记录步数的数组。

代码:

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <algorithm>

#include <iostream>

#include <queue>

#define N 10000+1000

#define M 10000



using namespace std;



int n, m;

bool vis[N];

int dis[N];



void bfs()

{

    queue<int>q;

    q.push(n);

    vis[n]=true;

    dis[n]=0;

    int cur;

    while(!q.empty())

    {

        cur=q.front(); q.pop();

        if(cur==m)

        {

            printf("%d\n", dis[cur]);

            return ;

        }

        else

        {

            if(cur-1>=0 && cur<=M && vis[cur-1]==false)

            {

                vis[cur-1]=true;

                q.push(cur-1);

                dis[cur-1]=dis[cur]+1;

            }

            if(cur*2>=0 && cur*2<=M && vis[cur*2]==false)

            {

                vis[cur*2]=true;

                q.push(cur*2);

                dis[cur*2]=dis[cur]+1;

            }

        }

    }

}



int main()

{

    scanf("%d %d", &n, &m);

    memset(dis, 0, sizeof(dis));

    memset(vis, false, sizeof(vis));

    bfs();

    return 0;

}
View Code

 

 

你可能感兴趣的:(codeforces)