CF 520B-Two Buttons-bfs求最少操作次数

Description

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 Input

4 6

Sample Output

2

题目大意:

给定两个正整数n,m。
有两个按钮,红色的和蓝色的,控制数值x的大小。红色按钮使x变为原来的两倍蓝色按钮使x减去1。问,至少按几次按钮可以使n变为m

核心思想:

有效的数值状态为1~2X104,因为如果数值增大到超过2X104的话,降到m的范围104所需要的次数肯定不是最优解。
任一状态的后继状态最多有两个,可以用搜索的方式来得到后继状态,用深搜还是广搜呢?题目要求至少按几次,广搜得到的答案恰好符合这一要求。
vis[i]标记数值 i 是否已被搜索过,避免重复搜索。

代码如下:

#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
const int N=2e4+20;
struct node{
	int x,cnt;
}q[N];
bool vis[N];
int bfs(int st,int en)
{
	int t=0,h=1;
	q[0].x=st;
	q[0].cnt=0;
	vis[st]=1;
	while(t<h)
	{
		int z=q[t].x;
		//达到终态 
		if(z==en)
			return q[t].cnt;
		//按蓝色按钮-1
		if(z>1&&!vis[z-1])
		{
			vis[z-1]=1;
			q[h].x=z-1;
			q[h].cnt=q[t].cnt+1;
			h++;
		}
		//按红色按钮*2
		if(z*2<N&&!vis[z*2])
		{
			vis[z*2]=1;
			q[h].x=z*2;
			q[h].cnt=q[t].cnt+1;
			h++;
		}
		t++;
	}
	return 0;
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	printf("%d\n",bfs(n,m));
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值