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;
}
.