CodeForces-1141A-Game 23

题目:

Description:

Polycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nnby 33. He can perform any number of moves.

Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.

It is easy to prove that any way to transform nn to mm 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 nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).

Output

Print the number of moves to transform nn to mm, 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.120→240→720→1440→4320→12960→25920→51840. The are 77steps in total.

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

In the third example, it is impossible to transform 4848 to 7272.

题意分析:

1.可以用DFS或者BFS,但是容易WA,注意判断范围,别超出去了

2.类似于思维解法,注意最后的判断,具体看代码

注意:

判断最终情况,不一定能被整除的就有答案

代码:

BFS:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#define N 500000000
using namespace std;
long long n,m;
bool flag=0;
struct ljh
{
	long long x,step;
}now,nextt;
void bfs()
{
	queue<ljh>q;
	now.x=n;
	now.step=0;
	q.push(now);
	while(!q.empty())
	{
		now=q.front();
		q.pop();
		if(now.x==m)
		{
			flag=1;
			printf("%lld",now.step);
			return;
		}
		for(int i=1;i<=2;i++)
		{
			if(i==1)
			{
				nextt.x=now.x*2;
				if(nextt.x==m)
				{
					flag=1;
					printf("%lld",now.step+1);
					return;
				}
				if(nextt.x<m)
				{
					nextt.step=now.step+1;
					q.push(nextt);
				}
			}
			else
			{
				nextt.x=now.x*3;
				if(nextt.x==m)
				{
					flag=1;
					printf("%lld",now.step+1);
					return;
				}
				if(nextt.x<m)
				{
					nextt.step=now.step+1;
					q.push(nextt);
				}
			}
		}
	}
	return;
}
int main()
{
	scanf("%lld%lld",&n,&m);
	if(m%n!=0)printf("-1");
	else
	{
	bfs();
	if(!flag)printf("-1");
    }
	return 0;
}

思维:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
LL x,y,k,ans=0;
int main()
{
	scanf("%lld%lld",&x,&y);
	if(y%x!=0)printf("-1");
	else
	{
		k=y/x;
		while(k%2==0)
		{
			k/=2;
			ans++;
	    }
	    while(k%3==0)
	    {
	    	k/=3;
	    	ans++;
		}
		if(k!=1) printf("-1");
		else printf("%lld",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Ljh_handsome/article/details/88874608
23