A. Game 23(简单搜索+map标记)---Codeforces Round #547 (Div. 3)

Game 23

time limit per test:1 second

memory limit per test:256 megabytes

题目链接http://codeforces.com/contest/1141/problem/A

Polycarp plays “Game 23”. Initially he has a number n and his goal is to transform it to m . In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn’t depend on the way of transformation).
Input

The only line of the input contains two integers n and m (1<=n,m<=5*108)
Output

Print the number of moves to transform n to m , or -1 if there is no solution.
Examples

Input
120 51840

Output
7

Input
42 42

Output
0

Input
48 72

Output
-1

Note

In the first example, the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.
The are 7 steps in total.

In the second example, no moves are needed. Thus, the answer is 0

In the third example, it is impossible to transform 48 to 72


题目大意:给你两个数n和m问你通过变换(n *2或n *3)将n变到m最少需要几步?如果无法做到输出-1。
简单的bfs。标记的时候由于n *2、n * 3会很大所以使用map来进行标记。
详细代码:

#include <cstdio>
#include <map>
#include <queue>
using namespace std;
int a[]={0,2,3};
int main()
{
	int n,m;
	scanf ("%d%d",&n,&m);
	queue<int>q,stp;
	map<int,int>mp;
	q.push(n),stp.push(0);
	if (n==m) {
		printf ("0\n");
		return 0;
	}
	mp[n]=1;
	int mark=0;
	while (!q.empty()){
		for (int i=1; i<=2; i++){
			int x=q.front()*a[i],y=stp.front()+1;
			if (x<=m && !mp[x]){
				mp[x]=1;
				if (x==m) {
					printf ("%d\n",y);
					return 0;
				}
				q.push(x);stp.push(y);
			}
		}
		q.pop(),stp.pop();
	}
	if (!mark) printf ("-1\n");
	return 0;
}

.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值