cf520B-Two Buttons 【BFS】

http://codeforces.com/contest/520/problem/B

 

Two Buttons

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.

 

思路:bfs搜索。这里bool数组是关键。

代码:

 1 #include <fstream>

 2 #include <iostream>

 3 #include <algorithm>

 4 #include <cstdio>

 5 #include <cstring>

 6 #include <cmath>

 7 #include <vector>

 8 #include <queue>

 9 #include <cstdlib>

10 

11 using namespace std;

12 

13 #define PI acos(-1.0)

14 #define EPS 1e-10

15 #define lll __int64

16 #define ll long long

17 #define INF 0x7fffffff

18 

19 struct node{

20     int t,cnt;

21     node(){}

22     node(int t,int cnt){

23         this->t=t;

24         this->cnt=cnt;

25     }

26 }tmp;

27 int n,m,ans=INF;

28 queue<node> q;

29 bool b[10005<<1];

30 

31 void bfs();

32 

33 int main(){

34     //freopen("D:\\input.in","r",stdin);

35     //freopen("D:\\output.out","w",stdout);

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

37     bfs();

38     printf("%d\n",ans);

39     return 0;

40 }

41 void bfs(){

42     q.push(node(n,0));

43     while(!q.empty()){

44         tmp=q.front();q.pop();

45         if(b[tmp.t]||tmp.t==0)    continue;

46         b[tmp.t]=1;

47         if(ans<tmp.cnt)  break;

48         if(tmp.t==m){

49             ans=min(ans,tmp.cnt);

50         }else if(tmp.t>m){

51             ans=min(ans,tmp.cnt+tmp.t-m);

52         }else{

53             q.push(node(tmp.t<<1,tmp.cnt+1));

54             q.push(node(tmp.t-1,tmp.cnt+1));

55         }

56     }

57 }

 

你可能感兴趣的:(button)